JavaScript: 'const' and 'let' (Don't use 'var' ever!)

Before 'const' and 'let' introduced, 'var' had been used for declaring variables. It caused a lot of issues. We understand we should not use the 'var' anymore. But why? Let's find out the reason through a simple example.

let

let age = 20;
let canDrink = false;

if (age > 18) {
    let canDrink = true;
    console.log(`Inside: ${canDrink}`);
}

console.log(`Outside: ${canDrink}`);

image.png

From outside of the bracket, we can't access the value that has been executed in the if statement.

What is going to happen if we still use the 'var'

var age = 20;
var canDrink = false;

if (age > 18) {
    var canDrink = true;
    console.log(`Inside: ${canDrink}`);
}

console.log(`Outside: ${canDrink}`);

image.png

You can notice that 'var' ignores scope completely. In order to write safe code and avoid confusion, we should stop using 'var'.

const

When you use 'const' for declaring a variable, you can't reassign the value. It helps us to prevent errors or bugs. Also, it prevents hackers access important valuables and change the values.

example 1

const numberOfDays = 7;
numberOfDays = 10;

image.png

example 2

const person = {
    name: 'Grace',
    age: '20',
    isEnrolled: false,
};

person = 'Anna';

image.png

However, when it comes to objects, you can change the properties.

'use strict';

const person = {
    name: 'Grace',
    age: '20',
    isEnrolled: false,
};

// person = 'Anna';

person.name = 'Anna';

console.log(person);

image.png