Variable shadowing, hoisting and the temporal dead zone

var x = 1;
function f() {
let x = x;
// Something that modifies x
};
f();

Variable shadowing

let x = 3;
if(x === 3) {
let y = 4;
console.log(x); // 3
console.log(y); // 4
}
console.log(x); // 3
console.log(y); // ReferenceError
let x = 3;
if(x === 3) {
let x = 4;
console.log(x); // 4
}
console.log(x); // 3

Hoisting

function f() {
console.log(x); // undefined
var x = 3;
console.log(x); // 3
}
function f() {
var x;
console.log(x); // undefined
x = 3;
console.log(x); // 3
}

The temporal dead zone

function f() {
console.log(x); // RefenceError
let x = 3;
console.log(x);
}
function f() {
let x;
// TDZ begins here
console.log(x); // ReferenceError
// TDZ ends here
x = 3;
console.log(x);
}

What’s wrong with my code?

var x = 1;
function f() {
let x = x;
// Something that modifies x
};
f();
var x = 1;
function f() {
let x;
x = x;
// Something that modifies x
};
f();
A Node.js session showing “ReferenceError: Cannot access ‘x’ before initialization” when my code is executed

What about var?

var x = 1;
function f() {
var x = x;
// Something that modifies x
};
f();

How can fix this?

var x = 1;
function f() {
let xCopy = x;
// Something that modifies xCopy
};
f();

Scope

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store