2

I have been reading some docs lately and came across some inconsistent patterns related to hoisting in JavaScript.

It goes as follows:

In functions,

function abc(){
 console.log("worked")
}

abc();

OUTPUT : worked

Also,

abc();
function abc(){
 console.log("worked")
}

OUTPUT : worked

This happens due to hoisting as in the execution context the memory is saved initially for abc.

But the same doesnt happen in case of varibles and I was wondering why

For example,

var a = "Hello"
console.log(a)

OUTPUT : Hello

**So why not the same in given below code?

console.log(a)
var a = "Hello"

The above code states "undefined"

when the execution starts for the above code:

  1. a is set to undefined
  2. then undefined is reassigned to the value provided that is "Hello"

But that is not the case, instead it outputs undefined

Why is that?

Thank you for reading. Any help would be really appreciated.

anshul
  • 661
  • 9
  • 27
  • See the [accepted answer](https://stackoverflow.com/questions/261599/why-can-i-use-a-function-before-its-defined-in-javascript) for this question. That'll explain to you the reason for the behavior of functions. – Ramesh Reddy Feb 27 '20 at 13:07

1 Answers1

2

The code

console.log(a)
var a = "Hello"

is interpreted as if it were written

var a;
console.log(a);
a = "Hello"

Why? That's the way the language is specified to work. Hoisting the whole initialization expression would create problems in many cases.

Pointy
  • 405,095
  • 59
  • 585
  • 614