JavaScript let statement

JavaScript let statement to declare a variable that are scoped to the nearest enclosing block. Another word we can say block scope variable.

let statement added in JavaScript 1.7 version and give a stable functionality in JavaScript.

If you don't assign variables value at declaration time, JavaScript automatically assigns the undefined value.

You can't use variable before the declaration otherwise gives an error.

Syntax

let variable_name = value;

Parameter

  • let : JavaScript reserved keyword.
  • variable_name: Name of the variable.
  • value: Optional, Initial value assign at the time of declaration.

Shorthand style, you can declare a one or more variables in single statement separated by comma.

let var1 = val1, var2 = val2, ..., varN = valN;

You need to define a script type and JavaScript version:

<script type="application/javascript;version=1.7"> ... </script>

let in functional scope: The following let statement example, variable scope within function,

<script type="application/javascript;version=1.7">
function callme() {
    let quote = "clever Boy";
    console.log("inside: "+ quote);
}

callme();
console.log("outside: "+ quote);
</script>

Run it...   »

let in loops: let variable visible in the for() loop block,

<script type="application/javascript;version=1.7">    
function callme() {
    for( let i = 1; i < 5; i++ ) {
        console.log(i);                          // i visible on here
    };
    console.log("Outside for block:", i);        // i not defined
}

callme();
</script>

Run it...   »

let variable visible in the if condition block,

<script type="application/javascript;version=1.7">
if (1){
    let i;
    for( i = 1; i < 5; i++ ) {
        console.log(i);    // i visible on here
    };
    console.log(i);        // i visible on here
}    
</script>

Run it...   »

let in global scope: Using let keyword to define variable globally. Once you define globally, you can access inside anywhere.

<script type="application/javascript;version=1.7">
let i = 1;
console.log("start----", i);
    
function callme() {
    for( i = 1; i < 5; i++ ) {
        console.log("looping time----",i);    // i visible on here
    };
    console.log("function end----", i); 
}  
 
callme();
console.log("end----", i);                    // i not define
</script>

Run it...   »

Browser Compatibility

  • Google Chrome 19+
  • Mozilla Firefox 2+
  • Internet Explorer 11+
  • Safari 3.2+

Note: Here details of browser compatibility with version number may be this is bug and not supported. But recommended to always use latest Web browser.

Google Chrome 19+ (50% partially supported), only when "Experimental JavaScript features" are enabled

  • In Google Chrome, Address bar type chrome://flags/: find and Enable Experimental JavaScript features.

Internet Explorer 11+ (80% partially supported) as per IE11 specification.

Opera not support.