By the end of this lesson, you will understand scope, hoisting, and the temporal dead zone in JavaScript.
Scope in JavaScript refers to the visibility of variables. It decides where variables can be accessed in your code. For example, if you declare a variable inside a function, it cannot be accessed outside of that function.
Let’s take a simple example.
function exampleFunction() {
let message = "Hello, World!";
console.log(message);
}
exampleFunction();
// Output: Hello, World!
// console.log(message); // Uncaught ReferenceError: message is not defined
File: scopeExample.js
Hello, World!
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during compile time. This means you can use variables before they are declared.
Here’s how hoisting works:
console.log(hoistedVar);
var hoistedVar = "This is hoisted!";
// Output: undefined
The temporal dead zone (TDZ) occurs when a variable is in scope but not yet initialized. If you try to access it before the declaration, you will get a ReferenceError.
Consider the following code.
console.log(tdzVar);
let tdzVar = "I'm in the TDZ!";
// Output: Uncaught ReferenceError: Cannot access 'tdzVar' before initialization
Create a function that demonstrates scope, hoisting, and the temporal dead zone by logging variables in different places. Try to place variable logs before their declarations.
function scopeAndHoisting() {
console.log(localVar);
var localVar = "Local variable";
console.log(localVar);
}
scopeAndHoisting();
// Output: undefined
// Local variable