This content originally appeared on DEV Community and was authored by Samuel K.M
Scoping:
- var is function-scoped or globally scoped if declared outside any function.
Example with var
(Function and Global Scope)
function varExample() {
if (true) {
var x = 10; // x is function-scoped
}
console.log(x); // Outputs: 10
}
varExample();
if (true) {
var y = 20; // y is globally scoped because it's outside a function
}
console.log(y); // Outputs: 20
- let and const are block-scoped, meaning they are only accessible within the block (delimited by {}) they are declared in.
Example with let
(Block Scope)
function letExample() {
if (true) {
let x = 10; // x is block-scoped
console.log(x); // Outputs: 10
}
console.log(x); // ReferenceError: x is not defined
}
letExample();
if (true) {
let y = 20; // y is block-scoped
console.log(y); // Outputs: 20
}
console.log(y); // ReferenceError: y is not defined
Example with const
(Block Scope)
function constExample() {
if (true) {
const x = 10; // x is block-scoped
console.log(x); // Outputs: 10
}
console.log(x); // ReferenceError: x is not defined
}
constExample();
if (true) {
const y = 20; // y is block-scoped
console.log(y); // Outputs: 20
}
console.log(y); // ReferenceError: y is not defined
Hoisting
Hoisting is like setting up a workspace before you start a task. Imagine you’re in a kitchen, preparing to cook a meal. Before you start cooking, you place all your ingredients and tools on the counter so they’re within reach.
In programming, when you write code, the JavaScript engine goes through your code before actually running it and sets up all the variables and functions at the top of their scope. This means that you can use functions and variables before you’ve declared them in your code.
All three (var, let, and const) are indeed hoisted. However, the difference lies in how they are initialized during the hoisting process.
var is hoisted and initialized with undefined.
console.log(myVar); // Outputs: undefined
var myVar = 10;
- let and const are hoisted but not initialized. This means they are in a “temporal dead zone” from the start of the block until the declaration is encountered.
console.log(myLet); // ReferenceError: Cannot access 'myLet' before initialization
let myLet = 10;
console.log(myConst); // ReferenceError: Cannot access 'myConst' before initialization
const myConst = 20;
Reassignment and Reinitialization:
var can be reinitialized (declared again) and reassigned (assigned a new value).
let cannot be reinitialized within the same scope but can be reassigned.
const cannot be reassigned; it must be initialized at the time of declaration. However, if the const is an object or array, the contents (properties or elements) of the object or array can be modified.
This content originally appeared on DEV Community and was authored by Samuel K.M