Difference between Var, Let, and Const, a simple definition

Javascript has been evolving, and it has had a long journey. ES6 is the latest javascript standard that is being adopted by the majority of developers in the world, but still, certain concepts are not evident among them.

Difference between Var, Let, and Const, a simple definition

One such addition in the ES6 is the new variable declarators, let and const. This article will be looking at how these new declarators differ from the older var keyword and each other.

We will also be discussing them concerning their scope and use.

Let us dive into it now.

Redeclaring and updating

All three of the keywords have their own rules when it comes to redeclaring and updating the variables.

With var, you can easily redeclare and update the variable.

Whereas with let, you can change the variable but declaring one with the same name throws an error.

Lastly, once a const variable has been declared and assigned a value, you cannot change it, nor can you redeclare it.

var foo = “abc”;
var foo = “abcd”; // Will work without issues

let bar = “foo”;
let bar = “foo2”; // SyntaxError: Identifier 'bar' has already been declared

const man = ”banana”;
man = ”apple” //Uncaught TypeError: Assignment to constant variable.
Difference btw var, let and const declarations

Scope

The scope of a variable tells us where Var, Let, or Const can use it.

Var has a different scope as compared to let and const. Var is globally scoped and locally scoped. If var is created outside of a function, it can be accessed anywhere. But if it is declared inside the function, it cannot be accessed outside of it.

var foo = 'abc'
function myFunc() {
	var boo = '123'
	console.log(foo);
}
console.log(boo) // Uncaught ReferenceError: boo is not defined
myFunc() // will print abc
Var Scope example

Let, and const, both are blocked scope, i.e., their scope lies within the curly braces. It can be a function, a switch statement, an if-else, or anything inside the braces.

let count = 4;
if (count > 3) {
	let goo = "Hi";
	console.log(goo);// "prints Hi instead"
}
console.log(goo) // Uncaught ReferenceError: goo is not defined
Let Scope example

Hoisting

When it comes to hosting, all declaration keywords are moved to the top of their scope before any execution happens. But the main difference is that var is assigned undefined value whereas, let, and const throw a reference error if used before the declaration.

console.log(my1) //undefined will be printed
console.log(my2) //Uncaught ReferenceError: my2 is not defined
var my1 = 20;
let my2 = 30;
Hoisting of Var and Let example

Conclusion

With these differences, you can advise using the new declarations from the ES6 to save you from many weird issues. Knowing the use of each declaration can make your code logically strong.

That is all, happy coding!