Languages
[Edit]
EN

JavaScript - how to use let keyword

1 points
Created by:
Eshaal-Wilkinson
774

In this article, we would like to show you how to use the let keyword in JavaScript.

Introduction

The let keyword has been introduced to JavaScript in ES2015. There are a few important things that should know for each programmer who wants to use let keyword.

1. let keyword syntax example

let syntax is similar to var

  1. variable declaration
    let a;
    let b;
    let c;
  2. variable declaration with value assigning
    let a = 1;
    let b = 2;
    let c = 3;
  3. if the variable is not assigned
    let a;
    let b;
    
    console.log(a === undefined); // true
    console.log(b === udeffined); // true

    Output:

    true
    true
  4. multiple variables declaration with one let keyword
    let a, b, c;
    
    console.log(a === undefined); // true
    console.log(b === undefined); // true
    console.log(c === undefined); // true

    Output:

    true
    true
    true
  5. multiple variables declaration with value assigning
    let a = 1, b = 2, c = 3;
    
    console.log(a); // 1
    console.log(b); // 2
    console.log(c); // 3

    Output:

    1
    2
    3

     

  6. multiple variables declaration, some with value assigning

    let a, b = 2, c;
    
    console.log(a); // undefined
    console.log(b); // 2
    console.log(c); // undefined

    Output:

    undefined
    2
    undefined

2. let keyword scope example

The scope of let is the nearest enclosing curly brackets.

let a = 1;

{ // this brackets create new scope for let keyword variables
    let a = 2;

    console.log(a); // 2
}

console.log(a); // 1

Output:

2
1

3. let keyword with for loop

When let keyword is used with for loop the scope of variable is for whole for statement.

for (let i = 0; i < 5; ++i) {
    console.log(i);
}

// i variable cannot be used here
// var keyword allowed to use variables here

Output:

0
1
2
3
4

4. Difference between let and var keywords

The difference has been described here.

5. Tips

  • ALWAYS use let keyword.

See also

  1. JavaScript - ECMAScript / ES versions and features

Alternative titles

  1. How to use let in JavaScript?
  2. JavaScript - How to use let?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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