Javascript Es6 Let Const And Block Scope Complete Guide
Understanding the Core Concepts of JavaScript ES6 Let, Const, and Block Scope
JavaScript ES6: Let, Const, and Block Scope
let
Keyword
The let
keyword allows you to declare a variable that is limited to the scope of a block, statement, or expression where it is used. Unlike var
, which is function-scoped or globally scoped depending on its context, let
provides block scoping, making your code more predictable.
Example:
if (true) {
let x = 10; // x is only accessible within this block
console.log(x); // 10
}
console.log(x); // ReferenceError: x is not defined
In the code above, x
is declared within an if
block. Outside of this block, attempting to access x
results in a ReferenceError
because x
is not defined outside its block scope.
const
Keyword
The const
keyword is used to declare constants, which are read-only and cannot be reassigned after their initial declaration. This does not mean the value it holds is immutable, only the reference to the variable cannot be changed. For example, if const
is an object, it can be modified but not reassigned.
Example:
const pi = 3.14;
pi = 3.14159; // TypeError: Assignment to constant variable.
const user = { name: 'John' };
user.name = 'Jane'; // This is allowed
user = {}; // TypeError: Assignment to constant variable.
The const
keyword is particularly useful when you want to ensure a variable doesn't get reassigned, enhancing code readability and maintainability. However, it's important to note that const
does not provide immutability by default, as objects and arrays can still be modified.
Block Scope
Block scope is a concept introduced in ES6 that limits the accessibility of variables to the block ({}) in which they are defined. Prior to ES6, using var
, a variable declared inside a function or block was accessible throughout the function or globally if declared outside any function.
Example:
function example() {
if (true) {
var y = 20;
let z = 30;
}
console.log(y); // 20
console.log(z); // ReferenceError: z is not defined
}
In this example, y
is declared using var
and is accessible outside its block scope, whereas z
is declared with let
and is confined to the block in which it is defined, resulting in a ReferenceError
when trying to access it outside this block.
Key Differences
Scope:
var
: function-scoped or globally-scoped.let
&const
: block-scoped.
Reassignment:
var
&let
: Reassignable.const
: Not reassignable, but mutable if it's an object or array.
Hoisting:
var
: Variables are hoisted to the top of their scope but are not initialized.let
&const
: Variables are hoisted but remain uninitialized until their declaration is processed, resulting in aReferenceError
if accessed before declaration (Temporal Dead Zone).
Global Object:
var
: Declared variables are properties of the global object (window
in a browser).let
&const
: Not added to the global object.
Online Code run
Step-by-Step Guide: How to Implement JavaScript ES6 Let, Const, and Block Scope
Understanding let
, const
, and Block Scope
1. var
in ES5
Before diving into let
and const
, it's useful to understand how var
works. var
has function scope, meaning a variable is accessible throughout the function in which it is declared, and not the code block.
function example() {
if (true) {
var a = 5;
}
console.log(a); // Output: 5
}
example();
2. let
in ES6
let
introduces block scope to JavaScript. A block is a chunk of code bounded by curly braces { ... }
. A variable declared with let
is only accessible within the block in which it is declared.
function example() {
if (true) {
let a = 5;
console.log(a); // Output: 5
}
console.log(a); // ReferenceError: a is not defined
}
example();
3. const
in ES6
const
is also block-scoped like let
. However, variables declared with const
must be assigned an initial value, and it cannot be reassigned. They are also read-only.
function example() {
if (true) {
const a = 5;
console.log(a); // Output: 5
// a = 10; // TypeError: Assignment to constant variable.
}
console.log(a); // ReferenceError: a is not defined
}
example();
4. Temporal Dead Zone (TDZ)
Variables declared with let
and const
are not hoisted like var
. This means you cannot access a variable before it has been declared. The time between the start of the block and the declaration is known as the Temporal Dead Zone (TDZ).
function example() {
console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 5;
}
example();
5. Reassignment and Re declaration
var
can be redeclared and reassigned.
var x = 1;
var x = 2;
console.log(x); // Output: 2
x = 3;
console.log(x); // Output: 3
let
can be reassigned but not redeclared.
let y = 1;
// let y = 2; // SyntaxError: Identifier 'y' has already been declared
y = 2;
console.log(y); // Output: 2
const
cannot be reassigned or redeclared.
const z = 1;
// z = 2; // TypeError: Assignment to constant variable.
// const z = 2; // SyntaxError: Identifier 'z' has already been declared
console.log(z); // Output: 1
6. Block Scope in Nested Blocks
Variables declared with let
and const
are only accessible within their respective blocks, even if they have the same name.
function example() {
let i = 1;
if (true) {
let i = 2; // different variable
console.log(i); // Output: 2
}
console.log(i); // Output: 1
}
example();
Complete Example
Here is a complete example that combines all these concepts:
Top 10 Interview Questions & Answers on JavaScript ES6 Let, Const, and Block Scope
1. What are let
and const
in JavaScript ES6?
Answer: In ES6, let
and const
were introduced to declare block-scoped variables. Unlike var
, which is function-scoped, let
and const
are scoped to the nearest enclosing block. let
allows you to reassign a variable’s value, whereas const
does not; however, if const
is used to declare an object or array, the contents of that can still be modified.
2. What is block scope in JavaScript ES6?
Answer: Block scope refers to variables being accessible only within the block they are defined, enclosed by curly braces {}
. It provides more precise control over the life span and visibility of variables, which reduces potential bugs related to variable hoisting and reassignment issues common with var
.
3. Why should I use let
instead of var
?
Answer: Use let
when you need a reassignable variable that is limited in scope to the block. Unlike var
, let
prevents variable hoisting within its block and avoids scope pollution, making your code easier to reason about and maintain.
4. Can I reassign a value to a variable declared by const
?
Answer: No, assigning a new value to a const
-declared variable after its initial assignment results in an error. However, const
does allow mutation of objects and arrays.
const myArray = [1, 2]; // Valid
myArray.push(3); // Valid - mutation allowed
const myObj = { a: 1 }; // Valid
myObj.a = 2; // Valid - mutation allowed
myArray = [1, 2, 3]; // Error - reassignment not allowed
myObj = { a: 2 }; // Error - reassignment not allowed
5. Does const
guarantee immutability?
Answer: No, const
only guarantees that the reference remains constant. For objects and arrays, the contents (properties and elements) can still be changed.
6. Are let
and const
hoisted in JavaScript ES6?
Answer: Yes, let
and const
are hoisted; however, accessing them before they are declared will result in a ReferenceError
due to the temporal dead zone
(TDZ) — the region of code where they are hoisted but cannot be accessed until declared.
7. How do let
, const
, and var
behave differently in terms of global variables?
Answer: When declared globally (outside
any function), var
creates a new property on the global object (window
in browsers). Both let
and const
do not create properties on the global object:
console.log(this); // Window { ... }
var a = 'var';
console.log(a); // 'var'
console.log(window.a); // 'var' - created property
let b = 'let';
console.log(b); // 'let'
console.log(window.b); // undefined
const c = 'const';
console.log(c); // 'const'
console.log(window.c); // undefined
8. Which one should you avoid using when creating variables in JavaScript ES6?
Answer: Typically, you should avoid var
because it can lead to unexpected behavior due to its function scoping and hoisting rules, causing hard-to-track bugs.
9. When should you use const
?
Answer: Use const
for variables that should remain constant throughout the program, such as configuration settings, constant values, or references to objects and arrays that shouldn’t be reassigned. Also, it can be used to ensure immutability in intent by preventing accidental reassignment.
10. What is the difference between let and var in ES6?
Answer: var
is function-scoped and has variable hoisting which can lead to unintuitive outcomes if not managed carefully. let
, on the other hand, is block-scoped and does not allow access to a variable before its declaration, avoiding hoisting pitfalls.
Login to post a comment.