let x = 20,
y = 10;
let result = add(x,y);
console.log(result);
function add(a, b){
return a + b;
}
Note: Modern JS engines actually employ numerous variations of both compilation and interpretation in the handling of JS programs.
Conclusion: JS is most accurately portrayed as a "Compiled" language
Scope is primarily determined during compilation
Why does it even matter whether JS is compiled or not?
Three stages of Code Compilation
var a = 2; ➝ var, a, =, 2, ;
Lexing is a subtle variation of Tokenizing in the sense that it identifies tokens in a stateful way.
Three stages of Code Compilation
Three stages of Code Compilation
⇨
Machine Instructions - to actually create a variable called a (including reserving memory, etc.), and then store a value into a.
Conclusion/Fact: Processing of JS programs occurs in (at least) two phases:
Compile-then-execute approach
Syntax Errors
var greeting = "Hello";
console.log(greeting);
greeting = ."Hi";
// SyntaxError: unexpected token .
JS engine first parses the entire program before any of it is executed
Syntax Errors
Syntax Errors
Early Errors
console.log("Howdy");
saySomething("Hello","Hi");
// Uncaught SyntaxError: Duplicate parameter name not
// allowed in this context
function saySomething(greeting,greeting) {
"use strict";
console.log(greeting);
}
strict-mode forbids duplicate params
Error thrown is not syntax error but early error in strict mode
Hoisting
function saySomething() {
var greeting = "Hello";
{
greeting = "Howdy"; // error comes from here
let greeting = "Hi";
console.log(greeting);
}
}
saySomething();
// ReferenceError: Cannot access 'greeting' before
// initialization
Accessing the greeting variable too early, a conflict referred to as the Temporal Dead Zone (TDZ)
var students = [
{ id: 14, name: "Kyle" },
{ id: 73, name: "Suzy" },
{ id: 112, name: "Frank" },
{ id: 6, name: "Sarah" }
];
function getStudentName(studentID) {
for (let student of students) {
if (student.id == studentID) {
return student.name;
}
}
}
var nextStudent = getStudentName(73);
console.log(nextStudent);
// Suzy
Target vs Source value
var a= 2;
Targets - 5
Sources - 7
function badIdea() {
eval("var oops = 'Ugh!';");
console.log(oops);
}
badIdea(); // Ugh!
In non-strict mode only.
eval compiles the string it has and executes it at runtime
Any vars or function declarations would modify its current scope of execution.
Performance Hit - Bad for already optimized code
var badIdea = { oops: "Ugh!" };
with (badIdea) {
console.log(oops); // Ugh!
}