Sub topic 1
Functions Are Values
Prerequisites
This chapter assumes you know basic JavaScript syntax and can declare and call functions. It also assumes you know var, let, and const, can work with arrays and objects, and have passed a function as a callback before.
Functions Are Values
In JavaScript, a function is a value, just like a number or an object. You can store it in a variable, pass it to another function, and return it from a function.
const greet = function (name) {
return `Hi, ${name}`;
};
function run(fn, arg) {
return fn(arg);
}
console.log(run(greet, 'Ada')); // 'Hi, Ada'Because a function can be returned, it can also outlive the call that created it. Closures depend on this.
Lexical Scope: Where Code Is Written Decides What It Sees
JavaScript uses lexical scope. A function's position in the source code decides which variables it can see. The place it is called from does not matter.
const x = 'global';
function outer() {
const x = 'outer';
function inner() {
return x;
}
return inner;
}
const fn = outer();
console.log(fn()); // 'outer'fn is called at the top level, but inner was written inside outer, so it reads outer's x.
Block Scope and Function Scope
var is function-scoped. It belongs to the whole enclosing function. let and const are block-scoped and exist only inside the nearest { }.
function demo() {
if (true) {
var a = 1;
let b = 2;
}
console.log(a); // 1
console.log(typeof b); // 'undefined'
}
demo();A common error is expecting var to stay inside an if block or a loop body. It does not.
How the Scope Chain Resolves Variables
When code reads a name, the engine looks in the current scope first, then in each enclosing scope, and finally in the global scope. It uses the first match it finds. If nothing matches, it throws a ReferenceError. An inner variable with the same name shadows, or hides, any outer one.
Lexical Environments Under the Hood
Each function call, and each block that declares let or const, creates a lexical environment. A lexical environment holds two things: a record of the local bindings and a reference to the outer environment. The scope chain is the series of these outer references.
When a function is created, it stores a reference to the environment it was created in. The spec calls this internal slot [[Environment]]. When the function runs later, its new environment points to that stored one. This is why inner still finds outer's x after outer has returned. The next chapter builds on this mechanism.
Exercise
What does this log, and why? let n = 1; function f() { return n; } function g() { let n = 2; return f(); } console.log(g());
Show answer
It logs 1. f was defined at the top level, so its outer environment is the global one. Lexical scope ignores the fact that g calls f.