DEV Community

Discussion on: Hoisting in JavaScript(Variables & function)

Collapse
 
unthrottled profile image
Alex Simons

Hey alright, variables in functions also get hoisted.

function dostThouEvenHoist() {
  console.log(`Hello hoist: ${toHoist}`);
  var toHoist = {
    "I am": "created in function definition",
  };
  return toHoist;
}
Enter fullscreen mode Exit fullscreen mode

What happens when the same variable is defined in different scopes in the same function and they both get hoisted?

function howDoIHoist(hoistOrNotToHoist) {
  console.log(`What happens here? ${whatHappensWhenIGetHoisted}`);
  if(hoistOrNotToHoist) {
    var whatHappensWhenIGetHoisted = {
      "I probably get hoisted": "Hoist Away!"
    };
    console.log(`Yes Hoist Please! ${JSON.stringify(whatHappensWhenIGetHoisted, null, 2)}`)
  } else {
    var whatHappensWhenIGetHoisted = {
      "Most likely Hoisted": "Don't hoist."
    };
    console.log(`Don't Hoist Please! ${JSON.stringify(whatHappensWhenIGetHoisted, null, 2)}`)
  }
}

howDoIHoist(true);
howDoIHoist(false);
Enter fullscreen mode Exit fullscreen mode

Thanks for the post!

Collapse
 
srishtikprasad profile image
Srishti Prasad • Edited

1st function call “howDoIHoist(true)” will print :-
What happens here? Undefined
And prints condition in “if” statement

This is because inside the scope of function “howDoIHoist()”,

“whatHappensWhenIGetHoisted” is variable and is used before it is defined. Hence,it will give “undefined”. According to the hoisting of variables which I’ve covered in this blog.

Image description

Moreover,“scope of a function” means the scope defined by the function's body, in which its local variables are declared

Variable “whatHappensWhenIGetHoisted” is inside a function so it is in the scope of that function. We can’t say here that variable “whatHappensWhenIGetHoisted” is in different scope if it used in if-else expression.

You can read more about Closure in my blog Link,here,I have covered this topic,it might be helpful for you!