Languages
[Edit]
EN

JavaScript - what is the difference between let and var?

4 points
Created by:
Dollie-Rutledge
476

This article was created to explain the difference beetween let and var keywords.

 

1. Main differences between let and var keywords are:

  • let keyword variables do not have variable hoisting.
    variable hoisting is shifting variable declarations to top of the source code making them accessible above.

    Example 1:
    <!doctype html>
    <html>
    <body>
      <script>
    
        'use strict';
    
        a = 2; // variable hosting allows for assigning before declaration
        console.log(a);
    
        var a;
    
      </script>
    </body>
    </html>

    Output:

    2


    Example 2:

    <!doctype html>
    <html>
    <body>
      <script>
    
        'use strict';
    
        var a = 2;
        console.log(a);
    
      </script>
    </body>
    </html>

    Output:

    2

     

  • let keyword variables can be created in different scopes:
     let keyword variablesvar keyword variables
    global scopeyesyes
    function scopeyesyes
    curly braces scopeyesno

2. Tips

  • use let keyword instead of var.

See also

  1. What is scope in JavaScript?

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join