logo CBCE Skill INDIA

Welcome to CBCE Skill INDIA. An ISO 9001:2015 Certified Autonomous Body | Best Quality Computer and Skills Training Provider Organization. Established Under Indian Trust Act 1882, Govt. of India. Identity No. - IV-190200628, and registered under NITI Aayog Govt. of India. Identity No. - WB/2023/0344555. Also registered under Ministry of Micro, Small & Medium Enterprises - MSME (Govt. of India). Registration Number - UDYAM-WB-06-0031863

JavaScript Let vs Var Keyword


JavaScript Let vs Var Keyword

In JavaScript, both let and var are used for variable declaration, but there are some key differences between them. Here are the main distinctions:

 

  1. Scope:

    • var is function-scoped, meaning it is visible throughout the entire function in which it is declared.
    • let is block-scoped, meaning it is only visible within the block (enclosed by curly braces) in which it is declared. This includes if statements, loops, and other code blocks.

    Example:

    function exampleScope() {
      if (true) {
        var x = 10; // Function-scoped
        let y = 20; // Block-scoped
      }
      console.log(x); // 10
      console.log(y); // ReferenceError: y is not defined
    }
  2. Hoisting:

    • Variables declared with var are hoisted to the top of their containing function or global scope. This means you can use a var variable before it is declared in the code.
    • Variables declared with let are also hoisted, but they are not initialized until the JavaScript engine reaches the line where they are declared. Accessing a let variable before its declaration results in a ReferenceError.

    Example:

    console.log(a); // undefined
    var a = 5;
    
    console.log(b); // ReferenceError: b is not defined
    let b = 10;

     

  3. Redeclaration:

    • Variables declared with var can be redeclared within the same scope without any error.
    • Variables declared with let cannot be redeclared within the same scope.

    Example:

    var c = 3;
    var c = 6; // No error with var
    
    let d = 5;
    let d = 10; // Error: Identifier 'd' has already been declared
  4. Temporal Dead Zone (TDZ):

    • The temporal dead zone is a behavior that occurs with let and const variables during the hoisting phase. In the TDZ, attempting to access the variable before its declaration results in a ReferenceError.

    Example:

    console.log(e); // ReferenceError: e is not defined
    let e = 15;

 

In modern JavaScript, it's generally recommended to use let and const over var due to the more predictable scoping behavior and to avoid issues related to hoisting. let is used for variables that will be reassigned, while const is used for variables that will not be reassigned after initialization.

 

Thank you.

Popular Post:

Give us your feedback!

Your email address will not be published. Required fields are marked *
0 Comments Write Comment