What is “let” statement in JavaScript?

Using the let statement, you can create Block scoped local variables in JavaScript. The let statement was introduced in the ECMAScript 6 standard of JavaScript.

Before ECMAScript 6, JavaScript had three types of scoping:

  • Global scoping
  • Functional scoping
  • Lexical scoping

To explore let statement in detail, consider the code snippet given below:


function foo() {
var x = 9;
if (x > 5) {
var x = 7;
console.log("Value of x in if statement = " + x);
}
console.log("Value of x outside if statement = " + x);
}
foo();

view raw

letstatpost1.js

hosted with ❤ by GitHub

You will get this output for the above code listing:

image

In the above listing, variable x is declared using the var statement. Hence, the scope of variable x is a function scope. Variable x inside the if statemnet is same variable x which was created outside the if statement. So, when you modify the value of variable x inside the if statement block, it modifies the value for all references of variable x in the function.

To avoid this, you need block-level scoping, and the let statement allows you to create a block-scoped local variable.

Let’s modify the above code snippet and use the let statement to declare the variable:


function foo() {
var x = 9;
if (x > 5) {
let x = 7;
console.log("Value of x in if statement = " + x);
}
console.log("Value of x outside if statement = " + x);
}
foo();

view raw

letstatpost2.js

hosted with ❤ by GitHub

In the above code snippet, you are declaring scope level local variable x using the let statement. Therefore updating value of variable x inside the if statement will not affect value of variable x outside the if statement.

Read full article on the Infragistics blog

2 responses to “What is “let” statement in JavaScript?”

  1. Thank u sir for this blog

  2. Is it the same if I change *var* in the beginning of the function to *let*?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com