DEV Community

Cover image for The Let Keyword
Moazam Ali
Moazam Ali

Posted on • Updated on

The Let Keyword

Let keyword

The let keyword declares variables that are limited to scope of block statements or expressions where it is used. It is used to declare block scoped variables that have a value parameter which is optional. They cannot be redeclared and must be declared first before use.
The let keyword was introduced in ES6 (2015).

Syntax

let name1 [= value1], name2 [= value2]  nameN [= valueN];
Enter fullscreen mode Exit fullscreen mode

Parameters
nameN:
It is the name of the variable

valueN (Optional):
It is the value that is to be assigned to the variable

Cannot be Redeclared

Variables that are declared with let cannot be redeclared, they will throw an Syntax error

SyntaxError: 'variableName' has already been declared
Enter fullscreen mode Exit fullscreen mode

Example:

let user = "John Carter";

let user = 5;

// SyntaxError: 'user' has already been declared
Enter fullscreen mode Exit fullscreen mode

Block Scope

Before ES6 (2015), JavaScript had only global scope and function scope. ES6 introduced two keywords, let & const, having block scope.

The body in between two curly braces {...} is called block scope. The let & const variables declared inside of {...} cannot be accessed from outside.

{
  let id = 1;
}
// id can NOT be used here
Enter fullscreen mode Exit fullscreen mode

Redeclaring Variables

Now as we know that let is a block scoped variable so its value would not affect variables declared outside of the block with the same name.

let color = Black;
// Here color is Black

{
    let color = Red;
    // Here color is Red
}

// Here color is Black
Enter fullscreen mode Exit fullscreen mode

Let Hoisting

JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code. Hoisting allows functions to be safely used in code before they are declared.

Variables defined with let are hoisted to the top of the block, but not initialized. Meaning: Using a let variable before it is declared will result in a ReferenceError:

color = "Black";
let color = "Red";

ReferenceError: Cannot access 'color' before initialization
Enter fullscreen mode Exit fullscreen mode

Conclusion

let is a signal that the variable may be reassigned, such as a counter in a loop, or a value swap in an algorithm. It also signals that the variable will be used only in the block it's defined in, which is not always the entire containing function.


Latest comments (0)