Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
JavaScript - Basic Structure
Closures in JavaScript
Using CSS in Javascript
OOPS in Javascript
Popup Window in Javascript
Printout a page in Javascript
Variable declaration in JavaScript
Difference of let, var and const
JavaScript - JSON Parse & Stringify

Difference of let, var and const



Let's break down the differences between let, var, and const in JavaScript:

Scope

  • var: Function-scoped. A variable declared with var is accessible throughout the function in which it is declared.

  • let and const: Block-scoped. Variables declared with let and const are only accessible within the block (enclosed by {}) in which they are declared.

Hoisting

  • var: Variables declared with var are hoisted to the top of their scope and initialized with undefined. This means they can be used before they are declared, but their value will be undefined until the declaration is encountered.

  • let and const: Variables declared with let and const are also hoisted, but they are not initialized until their declaration is encountered in the code. Accessing them before declaration results in a ReferenceError.

Reassignment

  • var and let: Both allow reassignment of their values.

  • const: Constants declared with const cannot be reassigned once they have been assigned a value. However, it is important to note that while the reference to the variable cannot change, the contents of the variable (if it's an object or array) can be modified.

Example

javascript
// var example
function varExample() {
    console.log(x); // undefined (due to hoisting)
    var x = 10;
    console.log(x); // 10
}

// let example
function letExample() {
    // console.log(y); // ReferenceError: Cannot access 'y' before initialization
    let y = 20;
    console.log(y); // 20
}

// const example
function constExample() {
    const z = 30;
    // z = 40; // TypeError: Assignment to constant variable
    console.log(z); // 30
    
    const arr = [1, 2, 3];
    arr.push(4); // Allowed
    console.log(arr); // [1, 2, 3, 4]
}

varExample();
letExample();
constExample();

Best Practices

  1. Use const by default: Declare variables using const unless you know their value will change.

  2. Use let if reassignment is needed: Use let for variables whose values are intended to be reassigned.

  3. Avoid var: var can lead to unexpected behavior due to its function-scoping and hoisting. It is generally best to use let and const.

In summary, prefer using let and const to benefit from block-scoping, and only use const when the variable's value should not be reassigned. This will help make your code more predictable and maintainable.




All rights reserved | Privacy Policy | Sitemap