At the beginning, when I was learning React, I made the mistake of not focusing on a few essential fundamentals. As my knowledge grew more substantial, I started learning those concepts and found myself more comfortable with React.
Many of my mentees discussed the challenges they faced when dealing with React which also centered around these fundamentals. So this motivated me to write this article and share what I've learned.
How to Use Let and Const in JavaScript
Until ES5, the only way to declare a variable was to use the var
keyword. ES6 introduced two more ways to declare variables, using the let
and const
keywords. Using these modern keywords gives us more predictability and fewer chances of introducing bugs in the code.
The var
Keyword
A variable declared with var
is function scoped. This means we will get a ReferenceError
when we try to access the variable outside of the function.
var x = 10;
function someFunc(){
var y = 10;
console.log('inside someFunc', x, y);
}
Now, if you call someFunc()
, it will log the following in the browser console:
inside someFunc 10 10
But try accessing the variable y outside of sumFunc()
and you will get the following error:
Uncaught ReferenceError: y is not defined
The let
keyword
let
is block scoped. This is the main difference between let
and var
. Take this function where we loop using a for
loop and access the variable i
inside and outside of the loop.
function letsLoop() {
for (var i=0; i<5; i++) {
console.log('i inside the loop: ', i);
}
console.log('i outside of loop', i);
}
When you call the function letsLoop()
, the output will be this:
i inside the loop: 0
i inside the loop: 1
i inside the loop: 2
i inside the loop: 3
i inside the loop: 4
i outside of loop 5
Now, let's change the keyword var
to let
while declaring and assigning the variable i
.
function letsLoop() {
for (let i=0; i<5; i++) {
console.log('i inside the loop: ', i);
}
console.log('i outside of loop', i);
}
If you execute the letsLoop()
function now, you will get a ReferenceError
while accessing the variable i
outside of the for
loop. It is because the visibility and accessibility (or scope) of the variable i
is limited to the for
block.
i inside the loop: 0
i inside the loop: 1
i inside the loop: 2
i inside the loop: 3
i inside the loop: 4
Uncaught ReferenceError: i is not defined
at letsLoop (<anonymous>:6:35)
at <anonymous>:1:1
The const
Keyword
const
is almost the same as let
. The only difference is that once you have assigned a value to a variable defined with the const
keyword, you can not reassign a new value to it.
const name = 'freeCodeCamp';
name = 'My freeCodeCamp'; // Uncaught TypeError: Assignment to constant variable.
This applies to all types of variables we can create in JavaScript. You need to be careful when it comes to a complex data structure like object
. When an object is declared and assigned value with const
, you can still change the value of its properties. But you can not reassign the variable another object. Please have a look:
const publication = {
'name': 'freeCodeCamp'
}
publication.name= 'My freeCodeCamp'; // Allowed
publication = {}; // Uncaught TypeError: Assignment to constant variable.
And now to compare the three keywords:
VAR | LET | CONST | |
---|---|---|---|
Scope | function | block | block |
Reassigning a new value | Allowed | Allowed | Not Allowed |
When accessed before declaring | undefined | ReferenceError | ReferenceError |
Here are some rules for using var, let, and const:
- Don't use
var
anymore. Uselet
orconst
. - Use
const
more often. Uselet
when you need to reassign another value to a variable.
In a React app, you will see code using let
and const
very often. A React component is usually declared using const
. Have a look at the example below.
The variable DifficultyLevels
is declared using const
and is assigned a function as a value. This function defines a React component. It makes sense to use const
here, as it will not be reassigned with another value.
Now, notice the usages of the variable level
inside the useEffect
. We need to reassign the values of it based on a condition. So it makes sense to use the let
keyword there. But, you won't see any var
anywhere!
const DifficultyLevels = () => {
const userDataLS = getFromLS(LS_KEY_USER_DATA);
const [userData, setUserData] = useState(userDataLS || {
'fullName': '',
'age': '',
'email': '',
'gender': 'F',
'difficultyLevel': BEGINNER
});
//... other code
useEffect(() => {
let level = 'beginner';
if (userData.age >=10 && userData.age <= 13) {
level = 'intermediate';
} else if (userData.age > 13) {
level = 'advanced';
}
setUserData({
...userData,
'difficultyLevel': level
});
}, [userData.age]);
//... other code
return(
<>
{/*...other code */}
<span> { userData.level } </span>
{/*...other code */}
</>
)
}