Understanding Let, Var, and Const in JavaScript
Hello Folks !
If you saw this article while Googling, I am going to make a wild guess that you are confused about the difference between var, let, and const in JavaScript (JS). Let's discuss how var, let, and const works and provide some examples.
It won’t be long, I promise.
JavaScript variables are containers for storing data values
let
and const
are two new features of ES6. Before that everyone was using var
var
var
can be at global scope and local scope. Just in case someone is wondering, var stands for “variable” in English (obviously 😆).
var greeting = 'Welcome to JS!'; // globally scoped
function myFunction() {
var favColor = 'Favorite color is purple'; // locally scoped
console.log(`My ${favColor}`);
// The `backtick`, as the template literal, is a new feature in ES6 to replace the complication of string concatenation.
}
console.log(greeting); // Welcome to JS!
console.log(favColor); // ReferenceError: favColor not defined
Global Scope : variable can be scoped outside of the function since it is defined outside of the function.
Local scope: variable is defined inside the function locally, therefore that variable cannot be called outside of the function. We can also update the var variable if you want.
var welcome = 'Welcome to Sweater Season';
console.log(welcome); // Welcome to Sweater Season!
welcome = 'Pumpkin Spice Latte!';
console.log(welcome); // Pumpkin Spice Latte!
We can redeclare the var
variable as well.
function fallActivities() {
console.log(activities) // undefined
var activities = 'buy a coffee';
console.log(`You can ${activities}.`); // You can buy a coffee.
}
And so, that’s var. As we can see, this statement provides all the flexibility needed for developers (But please, don’t overuse it!). So why do ES6 bother to introduce 2 more statements — let and const ? Let’s find out.
Let
let is my favorite and the most preferable way for variable declaration. let is block-scoped. A block is referring to anything within the curly braces {}.
It means the variable will be declared, existed and limited to use only inside block ({}), statement or expression and also available to its sub-block beside normal execution context (enclosing function, etc).
function testMe(){
while(true){
let x = 2;
break;
}
console.log(x); //ReferenceError: x is not defined
}
Yes to update:
let welcome = 'Welcome to Sweater Season';
console.log(welcome) // Welcome to Sweater Season
welcome = 'Pumpkin Spice Latte';
console.log(welcome) // Pumpkin Spice Latte
But will return an error if try to redeclare:
let welcome = 'Welcome to Sweater Season';
let welcome = 'Pumpkin Spice Latte! Halloween! Red Leaves!';
// SyntaxError: Identifier 'welcome' has already been declared
Another important difference from var is that variable hoisting doesn’t apply to let, which means during compile phase, let declaration will stay where it is and will not be processed first among other code — aka will not move to the top of context like var. Thus in executing this example,
x = 5;
y = 2;
let y;
var x;
it will yield ReferenceError again for y, but not for x. Finally, let doesn’t create a property on global object, unlike var when being used in the global context. So no messing around with global object by accident!!! 🚀
var x = 5;
let y = 4;
console.log(this.x); //5
console.log(window.x); //5
console.log(this.y); //undefined
console.log(window.y); //undefined
And unlike var, re-declaring a let variable will throw SyntaxError.
const
Since most of the things are covered in let, I will quickly go over const. const variables maintain constant values. Const is block-scoped.
Thus, it has all the restrictions of let such as: Declared variables are only available to use in inside block {} of code, statement, expressions beside the normal execution context. No variable hoisting applies to const. Declared variable can’t be re-declared.
const myConstant = {name: "Constant"};
myConstant = {name: "new Constant"}; //Error
myConstant.name = "new Constant"; //OK
console.log(myConstant.name); //new Constant
const arr = [1, 2];
arr = [2,3]; //Error
arr[0] = 2; //OK
console.log(arr); //[2,2]
Clear and easy to understand, isn’t it?
Advantages of let and const Avoid polluting our global object with unnecessary properties. Avoid hidden 🐛 — such as modifying a constant value by mistake, updating wrong variables which are in different scope block but declared with same name, etc… Avoid unnecessary hoisting.
Conclusion Before we say goodbye, let’s sum up what we just discussed:
var : function-scoped and can be updated and redeclared.
let : block-scoped, can be updated, but cannot be redeclared.
const : block-scoped, cannot be updated and redeclared.
*After all, who doesn’t like writing clean and safe code? *😃
If you like this post, don’t forget to give me a 👏 . It will surely motivate me a lot 😊
From a developer to developer