JavaScript let Keyword

JavaScript let Keyword

In this article, I am going to discuss JavaScript let Keyword with Examples. Please read our previous article where we discussed JavaScript this keyword in detail. At the end of this article, you will understand the what is JavaScript let keyword and when and how to use let keyword in JavaScript with examples.

JavaScript let Keyword:

In ES2015 two important new JavaScript keywords has introduced: let and const. These two keywords provide Block Scope for declaring variables (and constants) in JavaScript. Before ES2015, JavaScript had only two types of scope: Global Scope and Function Scope.

Global Scope Variables in JavaScript:

Variables declared outside the function (Globally) have Global Scope. Global variables can be accessible from anywhere in a JavaScript program. For example:

<html>
<head>
    <title>JavaScript Global Scope example</title>
</head>
<body>
    <p>A GLOBAL variable can be accessed from any script or function.</p>
    <p id="demo"></p>
    <script>
        var ScriptLang = "JavaScript";
        myFunction();

        function myFunction() {
            document.getElementById("demo").innerHTML = "I am Learning " + ScriptLang;
        }
    </script>
</body>
</html>

Output: I am Learning JavaScript

Function Scope Variables in JavaScript:

Variable declared inside the function (Locally) has Function Scope. Local variables can only be accessed from inside the function where they are declared. For example,

<html>
<head>
    <title>JavaScript function Scope example</title>
</head>
<body>
    <h3>JavaScript function Scope examplee</h3>
    <p>Outside myFunction() ScriptLang is undefined.local variables are not accessible outside the function</p>
    <p id="demo1"></p>
    <p id="demo2"></p>

    <script>
        myFunction();
        function myFunction() {
            var ScriptLang = "JavaScript";
            document.getElementById("demo1").innerHTML = typeof ScriptLang + " " + ScriptLang;
        }
        document.getElementById("demo2").innerHTML = typeof ScriptLang;
    </script>
</body>
</html>

Output:

Function Scope Variables in JavaScript

JavaScript let Keyword Properties:

JavaScript let Keyword Properties:

  • let creates a local variable in JavaScript & can be re-assigned.
  • Initialization during the declaration of a let variable is optional.
  • A let variable will contain undefined if nothing is assigned to it.
Example:
let count;
console.log(count); // Prints: undefined
count = 10;
console.log(count); // Prints: 10
Difference between var and let in JavaScript
  1. The let keyword is used to declare variables in JavaScript. The var keyword can also be used to declare variables, but the key difference between them lies in their scopes.
  2. var is function scoped while let is block scoped
  3. The var keyword allows you to re-declare a variable without any issue. However, re-declaring a variable using the let keyword will result in an error.
  4. It can be said that a variable declared with var is defined throughout the program as compared to let.
  5. The var variables belong to the global scope or local scope if they are declared inside a function. The let variables are blocked scopes.
  6. The global var variables are added to the global object as properties. The global object is window on the web browser. However, the let variables are not added to the global object:
Function Scope var and let Example:

Example=>var:

<html>
<head>
    <title>JavaScript Function Scope var keyword example</title>
</head>
<body>    
    <script>
        function func() {
            // x is known here but not defined.
            console.log('value of x here: ', x)
            {
                var x = 10;
                x = x + 5;
            }
            // x is still known here and has a value.
            console.log('value of x after for block: ', x)
        }
        // x is NOT known here.
        func()
    </script>
</body>
</html>

Output:

Function Scope var and let Example

In the code snippet above, the above example uses var, note how var is declared in line 11, inside a block. This variable is known (but undefined) above the block. However, it is known and defined after the block.

The highlighted lines represent the areas where x has a scope. Since it is the entire function itself, var is said to have function scope.

Example =>let:
<html>
<head>
    <title>JavaScript Function Scope let keyword example</title>
</head>
<body>
    <script>
        function func() {
            // x is NOT known here. Try uncommenting the line below.
            console.log('value of x here: ', x)
            {
                let x = 10;
                x = x + 5;
            }
            // x is NOT known here. Try uncommenting the line below.
            console.log('value of x after for block: ', x)
        }
        // x is NOT known here.
        func()
    </script>
</body>
</html>

Output:

Difference between var and let in JavaScript

In the second example that declares x using let in line 11, note that it is only known and defined within the block it is declared in – the highlighted lines. It is out of scope everywhere outside its block and JavaScript throws an error.

Block Scope let and var Example:

The below example will highlight the block scope for let more clearly.

Example=>let:

<html>
<head>
    <title>JavaScript Block Scope let keyword example</title>
</head>
<body>
    <script>
        let mango = "yellow"
        if (mango === "yellow") {
            let mango = "orange"
            console.log(mango)
        }
        console.log(mango)
    </script>
</body>
</html>

Output:

Block Scope let and var Example

Using let in JavaScript:

mango is declared as “yellow” in line7, and redeclared as “orange” in line 9 – inside the if block. However, as the output shows, the mango declared inside the if block has scope within that block only. Outside this block, the original mango variable set to “yellow” is available.

Example=>var:

<html>
<head>
    <title>JavaScript Block Scope var keyword example</title>
</head>
<body>
    <script>
        var mango = "yellow"
        if (mango === "yellow") {
            var mango = "orange"
            console.log(mango)
        }
        console.log(mango)
    </script>
</body>
</html>

Output:

Using let in JavaScript

Using var in JavaScript:

Conversely, in the code that uses var, re-declaration of mango to “orange” inside the if block, also changes the mango declared in line 7 to “orange“. This is because variables declared with var are defined globally, regardless of block scope.

From JavaScript version ES6, it is recommended that you should adapt let keyword and stop using the var keyword when you declare a variable.

In the next article, I am going to discuss JavaScript const keyword in detail. Here, in this article, I try to explain JavaScript let Keyword with examples. I hope this article will helps you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *