JavaScript 'let' and 'const' Keywords: JS Es6+ features
Understanding it in depth along with react context.
In this blog, I will be covering each π₯ essential JS ES6+ feature with clear explanations, definitions, real-world analogies, syntax, code examples, interview questions with answers, and exercises Plus, how they can be used in React projects!
Introduction
π Welcome to the Mastering React With Harshal Blog series! π
I'm on a mission to provide a comprehensive and practical understanding of React. π
By the end of the Mastering React series, you'll gain the knowledge and confidence to excel in React and overcome any obstacles. πͺ
Stay updated by following me along with subscribing to the newsletter so you Don't miss out on another blog!
let and const Keywords π
The let and const keywords were introduced in ES6 (ES2015) as alternatives to the traditional var for declaring variables in JavaScript. They provide 𧱠block-level scoping and help prevent unintended variable reassignments, contributing to more reliable and maintainable code.
Real-World Analogy π
Think of let
as having a whiteboard π³ where you can write and erase values whenever needed, while const
is like engraving a value on a stoneπͺ¨, making it permanent and unchangeable.
Syntax:
let variableName = value; // Mutable variable
const constantName = value; // Immutable constant
let
The let
keyword allows you to declare mutable variables with block-level scope. Variables declared with let
can be reassigned, making them suitable for values that are expected to change during program execution.
"mutable means something that can be changed or modified after it is created".
Example:
let count = 10;
count = 20; // Valid reassignment
if (true) {
let message = "Hello";
}
console.log(count); // Output: 20
console.log(message); // Error: message is not defined (due to block-level scope)
const
The const
keyword allows you to declare immutable constants with block-level scope. Once a variable is assigned with const
, its value cannot be reassigned or redeclared. It is best suited for values that remain constant throughout the program.
"Immutable means something that cannot be changed or modified after it is created."
Example:
const pi = 3.14;
pi = 3.14159; // Error: Assignment to constant variable
if (true) {
const message = "Hello";
}
console.log(pi); // Output: 3.14
console.log(message); // Error: message is not defined (due to block-level scope)
Real-World Project ExampleποΈ
Let's consider a React component that uses let
and const
to manage state and constants:
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};
const Greeting = () => {
const userName = "Harshal";
const pi = 3.14;
return (
<div>
<p>Hello, {userName}!</p>
<p>Value of Pi: {pi}</p>
</div>
);
};
Common Mistakes to Avoid π ββοΈ
Reassigning
const
Variables: Remember thatconst
variables cannot be redeclared or reassigned. Avoid attempting to change their value after initialization to prevent errors.Using
let
When Unnecessary: Only uselet
for variables that need to change during program execution. If a variable's value is meant to remain constant, useconst
it to make your intent clear.
Note π
Using 'const' with objects and arrays means you cannot change the variable to point to something else. However, it doesn't stop you from modifying the data inside the object or array. So, if you want the data to stay completely unchanged, 'const' alone might not be enough you might need to use extra measures like Object.freeze().
const person = {
name: 'John',
age: 30,
};
// This will work, even with 'const'
person.age = 35;
// For complete immutability, use Object.freeze()
Object.freeze(person);
// This won't have any effect
person.age = 40;
Interview Questionsβ
What is the difference between
let
andconst
in JavaScript?- Answer:
let
allows reassignment and is used for mutable variables, whileconst
is used for declaring immutable constants that cannot be changed after initialization.
- Answer:
Why is block-level scoping important, and how does it differ from function-level scoping?
- Answer: Block-level scoping provides better control over a variable lifetime, preventing unexpected variable hoisting and redeclaration issues. It differs from function-level scoping, where variables declared with
var
are limited to the function's scope.
- Answer: Block-level scoping provides better control over a variable lifetime, preventing unexpected variable hoisting and redeclaration issues. It differs from function-level scoping, where variables declared with
What happens when you use the 'const' keyword with an object in JavaScript? Does it prevent you from modifying the object's properties?
\=> Refer to note
Exerciseπ οΈ
Write a function that takes an array of numbers as input and uses let
to find the sum of all the numbers and const
to store the maximum value in the array.
Upcoming BlogsβοΈ
Arrow Functions and Lexical Scoping
Template Literals
Destructuring and Spread Syntax
Ternary Operator
Nullish Coalescing Operator
Optional chaining
Promises and Async/Await
This blog is part of the sub-series javascript Es6+ features of the main series Mastering React With Harshal Blog series