What is the basic difference between var, let and const?

What is the basic difference between var, let and const?

Beginners often times get confused about the variable declaration types in Javascript, when and how to use them. This article gives a straightforward perspective on the use of var, let and const.

The keywords var, let and const define variables in Javascript. Before 2015, var was the only way to declare a variable. let and const are new features of the 2015 EMCAScript 6 (ES6). First, I will briefly describe these concepts:

1. Function scope

A variable is defined inside the function locally, therefore that variable cannot be assessed outside of the function.

2. Block scope

A variable is only scoped inside of the curly braces i.e. {} and cannot be assessed anywhere out of the braces.

3. Global scope

A variable is defined and assessed outside of the function or block.

Difference between var, let and const

var

var is limited to the function which defines it. var reflects in a lot of ways as variables declared under var can be scoped globally and locally, or the term "function scope" .

function greetings() {
var sentence = 'Good day!' 
console.log(sentence) 
}

greetings() // 'Good day!'

console.log(sentence) // ReferenceError: sentence is not defined

var is not block scoped.

if (true) {
var sentence = 'Good day!'
}
console.log(sentence) // 'Good day!'

var variables can be re-declared; leading to errors if the programmer makes the mistake of re-declaring same variable names in the code.

var firstName = 'John'
var firstName = 'Peter' 
console.log(firstName) // 'Peter'

let

let is limited to the block defined by curly braces {}, let is block-scoped. If the variable is called outside of the block, it will give an error.

if (true) {
let sentence = 'Good day!'
console.log(sentence) // 'Good day!'
}
console.log(sentence) // ReferenceError: sentence is not defined

let can be updated but cannot be redeclared. This is a useful feature that prevents overriding of codes.

let firstName = 'John'
let firstName = 'Peter'
console.log(firstName) // SyntaxError: Identifier 'firstName' has already been declared 

let nickname = 'Bee' 
nickname = 'Bug'
console.log(nickname) // 'Bug'

const

Just like let, const is block-scoped and cannot be redeclared. However, a big difference is unlike let, const cannot be re-assigned. const is a constant!

const firstName = 'John' 
firstName = 'Peter'
console.log(firstName) // TypeError: Assignment to constant variable

To prevent avoidable bugs in Javascript, we use block-scoped variables instead of function-scoped variables. Hence, let and const are more applicable in the real world.

Happy coding!