JavaScript Let

  • In JavaScript, let is a variable declaration keyword. It was introduced in ES6 (ECMAScript 2015). When variables are declared with let, they will ALWAYS have block scope. Therefore, it should be declared before use. You can access it within its code block, but redeclaring it in the same block is impossible.

    Block Scope

    Before ES6 (ECMAScript 2015), there was no block scope; JavaScript only supported global scope and function scope. The block scope became part of JavaScript after the introduction of the let and const keywords

    Keep in mind that variables declared within a block { } are inaccessible from outside that block.

    HTML JavaScript

    Global Scope

    All var declared variables always have a Global Scope. Additionally, these variables can not have block scope. 

    Unlike let declared variables, if a variable is declared with var, you can access it from outside its block { }. 

    HTML JavaScript

    Redeclaring Variables

    Only variables declared with var can be redeclared. In contrast, let-declared variables can not be redeclared.

    HTML JavaScript

    Mind that, when redeclaring variables with the var keyword inside a block, the variables outside the block will also be redeclared.

    HTML JavaScript

    To avoid this problem, variables are redeclared with let, as it does not redeclare the variables outside the block.

    HTML JavaScript

    Difference Between var, let, and const

    KeywordScopeRedeclareReassignHoistedBinds this
    varnoyesyesyesyes
    letyesnoyesnono
    constyesnononono

    Perks

    • Both let and const have block scope.
    • You can not redeclare let and const.
    • Must declare let and const before use. 
    • let and const are neither hoisted nor bind to this.

    Downside

    • It is not necessary to declare var.
    • var is hoisted and binds to this. 

    Internet Explorer 11 and earlier versions do not support keywords let and const.

    Redeclaring JavaScript Variables

    var allows you to redeclare a variable at any time and in any part of the program.

    HTML JavaScript

    When the let keyword is used, it does not allow you to redeclare the variable in the same block.

    HTML JavaScript

    However, let allows you to redeclare a variable in another block.

    HTML JavaScript

    Let Hoisting

    In JavaScript, if a variable is declared with var, it will be hoisted to the top. Moreover, these variables can be initialized in the program at any moment, which means you can use them before declaring them.

    HTML JavaScript

    The variables declared with let are not initialized despite being hoisted to the top. Therefore, you can only access a let declared variable once it is executed.

    HTML JavaScript
  • HTML
    CSS
    JS
  • Ad #1
    Ad #2
    Scroll to Top