While developing with Javascript and going through pre-written code, you often come across let, var and const all used while declaring variables in Javascript.
The three are Javascript keywords that precede a variable name/identifier. These keywords are used to describe a variable's use, scope, and the ability to be re-declared or updated. Using either of the identifiers tells the compiler on how to handle the variable.
To differentiate the three keywords we will use three common aspects:
Scope
The scope of a variable defines the areas within the program from which the variable can be accessed.
Let and const have a block scope in that their use and accessibility are restrained to the block wherein the variable was declared.
A block is any part of the code enclosed within curly braces. ({}).
Var on the other hand is either on a global scope or a functional scope. If the variable is declared within a function, the variable is only accessible within the function. On the other hand, when defined outside a function the variable is visible and accessible anywhere throughout the program.
Ability to be updated
Any variable declared using the keywords let and var can be updated.
var name="faith";
name="ian";
console.log(name);
//ian
let name="faith";
name="ian";
console.log(name);
//ian
Values for variables declared using the const keyword cannot be updated.
const pi=3.14;
pi=3.142;
//error:Assignment to constant variable
However, for objects declared using the const keyword, the object elements value can be updated.
const person = { name: "Ali", age:20};
person.age=25;
Ability to be re-declared.
Variables declared using let and const cannot be re-declared. i.e:
let name="faith";
let name="ian";
//error: Identifier 'name' has already been declared
const pi=3.14;
const pi=3.142;
//error: Identifier 'pi' has already been declared
Variables declared using var keyword can be re-declared. i.e:
var name="faith";
var name="faith"; //acceptable
This is hazardous as it can lead to bugs in a program when the programmer re-declares the variable unknowingly. It is therefore safer to use let or const.
Below is a table that summarizes the differences between let, var, and const.
Thank you for reading! If the article was useful to you don't forget to like and share. Feedback is highly appreciated.