"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > An Overview of Let, Const, and Var: Key Differences Explained

An Overview of Let, Const, and Var: Key Differences Explained

Published on 2024-08-07
Browse:582

An Overview of Let, Const, and Var: Key Differences Explained

There was a time when I used and understood the practical use of let, const, and var in JavaScript, but explaining it in words was challenging. If you find yourself in a similar predicament the key points to focus on are the differences in scope, hoisting, reinitialization, and reassignment.

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). ### Example with var
var x = 10;
x = 20; // Reassignment
console.log(x); // Outputs: 20

var x = 30; // Reinitialization
console.log(x); // Outputs: 30

  • let cannot be reinitialized within the same scope but can be reassigned.
let y = 10;
y = 20; // Reassignment
console.log(y); // Outputs: 20

let y = 30; // SyntaxError: Identifier 'y' has already been declared
  • 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. ### Example with const
const z = 10;
z = 20; // TypeError: Assignment to constant variable.

const z = 30; // SyntaxError: Identifier 'z' has already been declared

Example with const Object

const obj = { a: 1 };
obj.a = 2; // Allowed, modifies the property
console.log(obj.a); // Outputs: 2

obj = { a: 3 }; // TypeError: Assignment to constant variable.

Example with const Array

const arr = [1, 2, 3];
arr[0] = 4; // Allowed, modifies the element
console.log(arr); // Outputs: [4, 2, 3]

arr = [5, 6, 7]; // TypeError: Assignment to constant variable.
Release Statement This article is reproduced at: https://dev.to/bazeng/an-overview-of-let-const-and-var-key-differences-explained-1ihi?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3