Hoisting is Dead: var vs. let vs. const

Reminder

Global variables 🤮

userName = 'Foo BAR';

console.log(userName); // Foo BAR

Use strict 😅

'use strict';

userName = 'Foo BAR'; // ReferenceError: userName is not defined
'use strict';

console.log(userName); // ReferenceError: userName is not defined

Hoisting

Variable hoisting

'use strict';

console.log(userName); // ???

var userName = 'Foo BAR';

Function hoisting

'use strict';

greetings(); // ???

function greetings() {
    console.log('HI!');
}

function greetings() {
    console.log('HELLO!');
}

A little bit better

'use strict';

greetings(); // TypeError: greetings is not a function.

var greetings = function () {
    console.log('HI!');
};

greetings(); // HI!

var greetings = function () {
    console.log('HELLO!');
};

greetings(); // HELLO!

let

Variables are only accessible after their declaration.

console.log(userName); // ReferenceError: userName is not defined

let userName = 'Foo BAR';

Variables are only accessible in the bloc where they are declared.

if (true) {
    let userName = 'Foo BAR';
}

console.log(userName); // ReferenceError: userName is not defined

const

const variables cannot be reinitialized.

const user = {
    firstName: 'Foo',
    lastName: 'BAR'
}

user = null; // TypeError: Assignment to constant variable.

const does not mean immutable.

user.firstName = 'John'; // OK!

It is recommended to declare all variables as const except if reusing the variable is inevitable.

This is less error-prone and avoids some common inattention mistakes.

const usage avoids clumsy variable reuse:

const user = {
    firstName: 'Foo',
    lastName: 'BAR'
}

/* 🤢*/
user = user.firstName; // TypeError: Assignment to constant variable.

Last updated