What will be the output?

let b = 'hello (*_*)'

function barFoo() {
	console.log('b from barFoo is', b);
	let b = 'hello';
}

barFoo();

It will throw a Reference Error. But why? we have already declared and initialised b on outer scope. So it might be available till we declare the b again. well thats not how things work in javascript, lets checkout hoisting.

What about this?

var b = 'hello (*_*)'

function barFoo() {
	console.log('b from barFoo is', b);
	var b = 'hello';
}

barFoo();

now the output is b from barFoo is undefined. Let’s check what’s happening.

Hoisting

JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code. — MDN1

So interpreter rearranges the declaration.

var b = 'hello (*_*)'

function barFoo() {
    var b;  // declaration
    console.log('b from barFoo is', b);
    b = 'hello'; // assignment
}

barFoo();

But why did there was reference error while using let?

Variables declared with let and const are also hoisted but, unlike var, are not initialized with a default value. An exception will be thrown if a variable declared with let or const is read before it is initialized.

  • MDN 2

checkout ECMA for additional addition information.


  1. Hoisting definition: MDN docs↩︎

  2. let and const hoisting: MDN docs ↩︎