Hoisting in JavaScript

Merna Zakaria
The Startup
Published in
4 min readOct 28, 2020

--

What is hoisting?

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution, regardless of whether their scope is global or local.

You should note that the hoisting mechanism only moves the declaration. The assignments are left in place.

In this article we will talk about:

  • Hoisting variables
  • Hoisting functions

Before dive into hoisting you must know undeclared variables do not exist until code assigning them is executed.
Therefore, assigning a value to an undeclared variable implicitly creates it as a global variable when the assignment is executed. This means that:

All undeclared variables are global variables.

So it is recommended to always declare variables regardless of whether they are in a function or global scope.

function hoist() {
a = 20;
var b = 100;
}

hoist();

console.log(a);
/*
Accessible as a global variable outside hoist() function
Output: 20
*/

console.log(b);
/*
Since it was declared, it is confined to the hoist() function scope.
We can't print it out outside the confines of the hoist() function.
Output: ReferenceError: b is not defined
*/

Hoisting variables

Var

The scope of a variable declared with the keyword var is its current execution context. This is either the enclosing function or for variables declared outside any function, global.

global variables

JavaScript has hoisted the variable within a global scope to the top of the scope, and initialized it with a value of undefined.

console.log(hoist); // Output: undefinedvar hoist = 'The variable has been hoisted.';--------------------------------------------------------------------var hoist;

console.log(hoist); // Output: undefined
hoist = 'The variable has been hoisted.';

Function scoped variables

The variable declaration, var message whose scope is the function hoist(), is hoisted to the top of the function.

To avoid this pitfall, we would make sure to declare and initialize the variable before we use it:

function hoist() {
console.log(message);
var message='Hoisting is all the rage!'
}

hoist(); // Output: undefined
--------------------------------------------------------------------function hoist() {
var message;
console.log(message);
message='Hoisting is all the rage!'
}

hoist(); // Output: undefined

Strict Mode

From its name, it is a restricted variant of JavaScript that will not tolerate the usage of variables before they are declare.Running our code in strict mode:

  1. Eliminates some silent JavaScript errors by changing them to explicit throw errors.
  2. Fixes mistakes that make it difficult for JavaScript engines to perform optimizations.

You may be missed out declaring variable, use strict has stopped you by throwing a Reference error.

'use strict';

console.log(hoist); // Output: ReferenceError: hoist is not defined
hoist = 'Hoisted';

We discussed Variables deceleration in ES5, let’s see variables deceleration in ES6

let

Variables declared with the keyword let are block scoped and not function scoped. It just means that the variable’s scope is bound to the block in which it is declared and hoisted to the top of this block, not the function in which it is declared.

let hoist;

console.log(hoist); // Output: undefined
hoist = 'Hoisted'

const

The const keyword allow us to make variables are immutable. That is, variables whose value cannot be modified once assigned.

With const , the interpreter throws an error if we use a constant before declaring and initializing it.

const PI = 3.142;

PI = 22/7; // Let's reassign the value of PI

console.log(PI); // Output: TypeError: Assignment to constant variable.
--------------------------------------------------------------------const PI;
console.log(PI); // Ouput: SyntaxError: Missing initializer in const declaration
PI=3.142;
--------------------------------------------------------------------function getCircumference(radius) {
console.log(circumference)
circumference = PI*radius*2;
const PI = 22/7;
}

getCircumference(2) // ReferenceError: circumference is not defined

a constant variable must be both declared and initialized before use.

Variables declared with let and const remain uninitialized at the beginning of execution while variables declared with var are initialized with a value of undefined.

Hoisting functions

JavaScript functions are classified as the following:

  1. Function declarations
  2. Function expressions

Function declarations

Function declarations are hoisted completely to the top. So we can invoke a function before declaring it.

hoisted(); // Output: "This function has been hoisted."function hoisted() {
console.log('This function has been hoisted.');
};

Function expressions

Function expressions are not hoisted, and the interpreter throws a TypeError since it sees expression as a variable and not a function.

expression(); //Output: "TypeError: expression is not a functionvar expression = function() {
console.log('Will this work?');
}

Order of precedence

It’s important to keep in mind when declaring JavaScript functions and variables.

  1. Variable assignment takes precedence over function declaration
  2. Function declarations take precedence over variable declarations

Variable assignment over function declaration

var double = 22;function double(num) {
return (num*2);
}
console.log(typeof double); // Output: number

Function declarations over variable declarations

var double;function double(num) {
return (num*2);
}
console.log(typeof double); // Output: function

Conclusion

It is important to understand hoisting in JavaScript when declaring variables and functions, hoisting mechanism only moves the declaration, but the assignments are left in place.

Function declarations are hoisted over variable declarations but not over variable assignments.

References

I hope this article is useful for you, thank you for your time.

--

--