← JavaScript Interview Questions

What is hoisting in JavaScript?

2
1
Asked 5 years ago by Hayk Hovhannisyan

Answers

Variable and function declarations in JavaScript are hoisted, which means that they are available in entire scope were they are defined.

Examples:

var a = 1;
console.log(a, b); // 1, undefined
var b = 2;
console.log(c); // Reference error

In the example above variable b is available since it's defined in the scope, but the value is undefined since it's set a line below. However variable c throws an error since it's not declared.

The same works for functions:

console.log(a()); // 1
function a() {
  return 1;
}

Pay attention that this works only for function declarations. If you assign to a variable function expression, it behaves like a regular variable.

console.log(a); // undefined
console.log(a()); // TypeError: a is not a function
var a = function() {
  return 1;
}

Scope:

The variable declared by var keywords and for function declarations will be available in the global scope by default, so they will be accessible in the entire application. In case module system is used (like CommonJS modules) the the declarations will be in the module scope. In case it's declared are inside a function they will be available only in the function scope.

(function () {
  var a = 1;
  console.log(a); // 1
})();
console.log(a); // Reference error

ES2015+ (ES6+)

In ES2015 let and const were introduced and they are block scoped. For simplicity we can say they are available only in the closest curly braces.

if (true) {
  const a = 1;
  console.log(a); // 1
}
console.log(a); // Reference error

let and const variables are also defined in the whole scope, but you can not use them before the line where they are actually declared.

console.log(a);
let a = 1; // ReferenceError: Cannot access 'a' before initialization

0
Answered 5 years ago by Hayk Hovhannisyan