Scoping and Hoisting in JavaScript

Naveen Karippai
2 min readNov 5, 2016

--

A scope can be defined as the context in which a variable exists. The scope can be local, or global in JavaScript.

Do you know the value logged on the JavaScript console when the following code snippet is run?

The answer here is “The Flash”. This happens due to Function-level scoping in JavaScript on the variable declaration (using var keyword). Developers from a Java background may find this surprising!

Function-level Scope

In JavaScript, variables declared (using var keyword) are function-level scoped. The block-level scoping with loops and conditionals ( if,for, while, switch blocks) don’t delimit the scope.

Hoisting

In JavaScript, hoisting is a powerful and expressive feature by which, the JavaScript interpreter moves the function and variable declarations to the top of the current referenced scope. The variable declarations and function declarations are hoisted in JavaScript!

The function body is hoisted along with the function declaration. In the code snippet, the function declaration is moved to the top of the scope through hoisting (above return statement). The equivalent code interpreted would be:

An aside:

The assignment part of variable and function expressions is not hoisted, but only the declarations are!

The equivalent code interpreted would be:

What’s new in ECMAScript 2015 (ES6)?

ECMAScript 2015 introduced keywords: let and const for block-level scoping in JavaScript.

The variables declared with let or const keyword has the block in which they are declared, as well as any continued sub-blocks as their scope.

Hoisting in ES6

In ECMAScript 2015, let and const keyword variable declarations will hoist the variable to the top of the block. However, referencing the variable in the block before variable declaration results in ReferenceError . The difference between var/function declarations and let/const declarations is in the initialization portion. The former are initialized with undefined or generator function right when binding is created at top of the scope, while the latter stay uninitialized until let/const statement is run. The variable is called to be in a “temporal dead zone” from the start of the block until the declaration is executed.

variable declaration keywords: ‘var’ v/s ‘let’

This happens due to the block-level scoping of let variable declaration.

Summary: Hoisting is a very powerful feature in JavaScript language. This provides high flexibility to the language if used necessarily. Also, a strong understanding of scoping in JavaScript can help us to avoid many common mistakes.

--

--