You make a variable message inside a function, then print it outside that function. The result is the error ReferenceError: message is not defined, even though you clearly made the variable. The variable does exist. You are only looking for it in the wrong place.
Every variable has an area where it can be used, called its scope. A variable made outside every function can be read from anywhere. A variable made inside a function or inside { } can be used only inside it. This lesson also covers hoisting: before it runs the first line, JavaScript notes down every declaration (every variable and function the code makes).
Global and function: inside can see out, outside can't see in
In this code, city is made outside the function and message is made inside it:
let city = "Leeds";
function printCity() {
let message = "I'm in ";
return message + city;
}
console.log(printCity()); // I'm in Leeds
console.log(message); // ReferenceError: message is not defined
cityis made outside every function, so it is a global variable: it can be read from anywhere, including from insideprintCity. The function doesn't need its own copy.messageis made inside the function, so it exists only there. This is called function scope.- From outside the function,
messageis not known. The last line tries to read it, and the result is aReferenceError: the error that means "this name doesn't exist here".
The rule goes one way: code inside a function can read the variables outside it, but code outside can't read the variables inside it.
Blocks: let and const stop at { }
This code has two variables named x: one outside the { } and one inside.
let x = 1;
{
let x = 2;
console.log(x); // 2
}
console.log(x); // 1
- A pair of
{ }makes a block. Examples are the body of anifor afor(two instructions you will learn later), or a{ }on its own as in this code. letandconstvariables exist only inside the block where they are made. This is called block scope. Thexinside the block is a different variable, separate from thexoutside.- So the code prints
2, then1.
var doesn't stop at the edge of a block, only at the edge of a function. { var y = 1; } followed by console.log(y) still prints 1, because y leaks out of the block. That is one reason to avoid var.
Hoisting: declarations are noted down first
This code uses three names before the lines that make them: var a, the function greet() and let b. Each one gives a different result:
console.log(a); // undefined
var a = 5;
greet(); // Hello!
function greet() {
console.log("Hello!");
}
console.log(b); // ReferenceError
let b = 10;
var ais noted down first and givenundefinedright away. The 5 only goes in when the second line runs. Soconsole.log(a)on the first line is not an error, it just printsundefined.- A function declaration (a function written with
functionin front) is noted down together with its body, sogreet()can be called before its line. A function stored in a variable, likeconst greet = function () {...}, can be called only after its line. let b(andconst) is noted down too, but it can't be used until its line has run. The part of the code before that line is called the Temporal Dead Zone (TDZ), and reading the variable there causes aReferenceError.
Closures: functions that remember their variables
A function is a value too, so a function can return another function. The returned function (the inner function) still remembers the variables of the scope where it was made:
function makeSavings() {
let balance = 0;
return function () {
balance = balance + 10;
return balance;
};
}
const deposit = makeSavings();
console.log(deposit()); // 10
console.log(deposit()); // 20
makeSavingsmakesbalance, then returns a function.const deposit = makeSavings();stores that function.- The inner function can read and change
balance, even thoughmakeSavingshas finished running. A function that still remembers the variables outside it is called a closure. balanceis made only once, whenmakeSavings()is called. That is why everydeposit()continues from the count before it.balancegoes up first and is returned after that, so the first call gives 10. In the exercise, the count goes up by 1, not 10: in this code that isbalance++(short forbalance = balance + 1) on its own line, beforereturn balance;.
⚠️ A balance that won't go up, and a variable that gets hidden
- The counter made inside the inner function. If
let balance = 0moves into the returned function,balanceis made again on every call. The result is always 10. return balance++. This form returns the value ofbalancefrom before it went up. Add first, thenreturn balance.- A new variable with the same name inside the function.
let city = ...insideprintCityhides the globalcity: inside the function,citymeans the new variable. To read the global one, just writecitywithoutlet.
TL;DR: Scope is the area where a variable can be used. A global variable (made outside every function) can be read from anywhere, a function's variable only inside that function, and let or const only inside the { } where it is made. var leaks out of a { } block. Hoisting means JavaScript notes down every declaration before it runs the code. Before the line that makes it, a var holds undefined, a let or const causes a ReferenceError (the Temporal Dead Zone), and a function declaration (a function written with function in front) can already be called. A closure is a function that was returned by another function and still remembers the variables outside it.
⚡ Inside can see out, outside can't see in
Write:
let city = "Leeds";
function printCity() {
let message = "I'm in ";
return message + city;
}
console.log(message); // ReferenceError
Meaning: Scope is the area where a variable can be used. city is made outside every function (a global variable), so it can be read from inside the function. message is made inside the function, so it exists only there: reading it from outside causes a ReferenceError (the name is not known). let and const variables also exist only inside the { } where they are made.
⚡ Declarations are noted down first
Write:
console.log(a); // ?
var a = 5;
Guess first: is the first line an error, or does it print something?
It prints undefined. var a is noted down first, before the code runs, and given undefined right away. The 5 only goes in when the second line runs.
Meaning: This is called hoisting: JavaScript notes down every declaration (every variable and function the code makes) before it runs the first line. let and const variables are noted down too, but reading one before its line causes a ReferenceError. The part of the code before that line is called the Temporal Dead Zone.
⚡ Functions that remember their variables
Write:
function makeSavings() {
let balance = 0;
return function () {
balance = balance + 10;
return balance;
};
}
const deposit = makeSavings();
deposit(); // 10
deposit(); // ?
Guess first: what does the second call give?
20. balance is made only once, when makeSavings() is called. So every deposit() continues from the count before it.
Meaning: makeSavings returns a function, which is stored in deposit. That function still remembers the variable balance, even though makeSavings has finished running. A function that still remembers the variables outside it is called a closure.