Simple answers to interview questions: Hoisting in JS

Simple answers to interview questions: Hoisting in JS

Preparing for a coding interview can be a little difficult. You prepare so you can make a good impression on the interviewer proving you have enough knowledge of important concepts.

Hoisting is one of the key concepts in Javascript. I've found it very confusing while it has a pretty direct definition and explanation, I always get the coding exercises wrong.

What is hoisting?

Hoisting is the moving of variables & functions to the top of the global or function scope where we define that variable or function.

What this means is during compilation, variables & functions are moved to the top of their respective scope.

console.log(name); 
var name = 'My name is Amy';

console.log(shoutOut()); 
function shoutOut(){
  console.log('Shout out to hash node boot campers');
}

From my understanding of the definition, console.log(name) should display My name is Amy and the function shoutOut should display "Shout out to hash node boot campers". This is not the case when you run this code though.

console.log(name); // undefined
var name = 'My name is Amy';

console.log(shoutOut());  // Shout out to hash node boot campers
function shoutOut(){
  console.log('Shout out to hash node boot campers');
}

Why does console.log(name) return undefined if it gets hoisted to the top? The reason is this

Variables are partially hoisted while functions are fully hoisted.

What this means is during the creation phase, the JavaScript engine allocates memory space to keywords with var or function and since variables are not fully hoisted, we hoist the variables but not the right side which assigns the variable to a value.

giphy (1).gif

Using this knowledge, it's clear that var name gets hoisted to the top but is not assigned any value.

console.log(name); //undefined
var name = 'My name is Amy';

console.log(shoutOut()); //shout out to hashnode bootcampers
function shoutOut(){
  console.log('Shout out to hashnode bootcampers');
}

Using the initial code example, if we modify the code like this

console.log(name); //undefined
var name = 'My name is Amy';

console.log(shoutOut()); //reference error shoutOut is not defined
(function shoutOut(){
  console.log('Shout out to hashnode bootcampers');
});

We get an error because the keyword function is hidden so the function doesn't get hoisted.

When we have function expressions like in this example, the variable shoutOut is hoisted to the top with a value of undefined;

console.log(name); //undefined
var name = 'My name is Amy';

console.log(shoutOut()); //error shoutOut is not a function
var shoutOut = function(){
  console.log('Shout out to hashnode bootcampers');
});

Hope this helps you understand hoisting a little better