Understanding the difference between var, let, and const is crucial for any JavaScript developer, especially for beginners. These keywords are used for variable declaration, but they differ in terms of scope, hoisting, and reassignment.

Advertisement

1. var

  • Scope: var is function-scoped. This means that a variable declared with var is available throughout the function it is declared in.
  • Hoisting: Variables declared with var are hoisted, meaning they are moved to the top of their scope. However, only the declaration is hoisted, not the initialization.
  • Reassignment: You can reassign and redeclare variables declared with var.
    
    function exampleVar() {
        if (true) {
            var x = 5;
        }
        console.log(x); // Outputs 5 as x is function-scoped
    }
    
    

2. let

  • Scope: let is block-scoped. A block is a chunk of code bounded by {}. A variable declared with let can only be accessed within the block it was declared in.
  • Hoisting: let declarations are hoisted but not initialized. Accessing them before the declaration results in a ReferenceError.
  • Reassignment: Variables declared with let can be reassigned but not redeclared within the same scope.
    
    function exampleLet() {
        if (true) {
            let y = 5;
            console.log(y); // Outputs 5
        }
        // console.log(y); // ReferenceError: y is not defined
    }
    
    

3. const

  • Scope: Like let, const is also block-scoped.
  • Hoisting: Similar to let, const declarations are hoisted but not initialized.
  • Reassignment: A const variable cannot be reassigned or redeclared. However, objects or arrays declared with const can have their properties or elements altered.
    
    function exampleConst() {
        const z = 10;
        // z = 5; // TypeError: Assignment to constant variable.
        const obj = { key: 'value' };
        obj.key = 'newValue'; // Allowed
    }
    
    

4. Comparison Table

Here’s a comparison table in HTML format that showcases the differences between var, let, and const in JavaScript:

Featurevarletconst
ScopeFunctionBlockBlock
HoistingYesNoNo
ReassignmentYesYesNo
RedeclarationYesNoNo

5. Examples

Here is a few practical example demonstrates the different scopes and behaviors of var, let, and const in JavaScript. Understanding these differences is fundamental for effective and error-free JavaScript coding.

Example 1: var in loops


for (var i = 0; i 

Description:

  • In this example, we declare a variable i using var inside a for loop.
  • Since var is function-scoped and not block-scoped, the variable i is accessible outside of the loop block.
  • After the loop completes, the value of i becomes 5 (as the loop increments i from 0 to 4, and it stops when i is 5).
  • Therefore, when we console.log(i) outside the loop, it outputs 5.

Example 2: let in loops


for (let j = 0; j 

Description:

  • Here, j is declared with let within a for loop.
  • let provides block scope, which means j is only accessible within the loop block.
  • Trying to access j outside its block (console.log(j)) results in a ReferenceError, as j is not visible outside the loop.

Example 3: const with objects


const person = { name: "John" };
person.name = "Jane"; // Allowed
// person = { name: "Doe" }; // TypeError: Assignment to constant variable.

Description:

  • person is an object declared with const, meaning you can't reassign the person variable itself.
  • However, objects declared with const can have their properties modified. That's why person.name = "Jane" is allowed and changes the name property of the person object from "John" to "Jane".
  • Attempting to reassign person itself (like person = { name: "Doe" }) will result in a TypeError since const doesn't allow reassigning the entire variable.

6. Practice Questions

  1. What will be the output of the following code and why?
    
    var a = 20;
    {
        let a = 30;
        console.log(a);
    }
    console.log(a);
    
    
  2. Predict the output:
    
    for (var i = 0; i 
    
  3. Can you declare a constant object in JavaScript and later change its properties? Provide an example.
  4. What is the difference in the scope of a variable declared with var inside a loop and let inside the same loop?
  5. Write a code snippet to demonstrate variable hoisting using var and let.

Feel free to answer these questions in the comments to test your understanding!

Share.

2 Comments

Leave A Reply

Exit mobile version