function declaration wins or variable declaration in JavaScript Hoisting

If you have a variable and a function declared with the same name, then which has a precedence over each other in the hoisting ?

This video explains that.

In JavaScript function and variable declarations are hoisted at the top of the execution context. You need to remember these three rules for on the same.

  1. variable and function declaration are hoisted at the top of the execution context.
  2. Only declaration gets hoisted, assignments does not get hoisted. Assignment happens where variable was declared.
  3. function declaration has a precedence over variable declaration in the hoisting.

if function and variable has same name, function will be hoisted before variable. Due to this reason below code prints 1 and 9

foo(); //1 

var foo = 9;

function foo(){

  console.log("1");
}

console.log(foo);

I hope now you understand hoisting in JavaScript in a better way. Please like and subscribe the channel.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s