Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explain the following examples? Hoisting?

I tried to explain the problem with the javascript hoisting, but I couldn't explain the case of b.

Didn't b = 50 modify the global variable b?

Is it the reason for block-level scopes?

Environment

Chrome 77

{
  a = 50
  function a() {}
}
console.log(a) //  50
console.log(b) // undefined
{
  console.log(b) // f b () {}
  function b() {}
  b = 50
  console.log(b) // 50
}
console.log(b) // ƒ b () {}

I thought b was 50 like a. but it was a function.

like image 484
Annani Zhu Avatar asked Jan 27 '26 16:01

Annani Zhu


1 Answers

2 important things are happening here

  1. Hosting happens in a function - placing anything inside {} considered as a block, not a function.
  2. Function declarations are hoisted over variable - hence if var and function have the same name, function will get preference

console.log(x); // f() {} //hoisted with assignment since "x" is function
var x = 90;
function x() {}

console.log(a); // undefined // hoisting of child block-scope variable is never assigned not even if "a" is function
{
    console.log(a); // f(){}
    a = 50; //**while execution //since global scope "a" not assigned yet it takes the first assignment in this child-block
    console.log(a); // 50 // because value has been assigned to "a" already
    function a(){} // Ignored //function "a" was never hoisted over variable assignment
    console.log(a); // 50 // block scope has "a=50" attached to it
}
console.log(a); // 50 // global scope also has "a=50" attached to it


console.log(b) // undefined // hoisting of child block-scope variable is never assigned not even if "a" is function
{
  console.log(b) // f () {}
  function b() {} // While hoisting global scope and this block scope get "b" attached to their scope as a function
  b = 50 // var b is reassigned, but "b" attached to this block is only reassigned, since type is changed globally attached "b" is not reached
  console.log(b) // 50
}
console.log(b) // ƒ () {} // globally attached "b" is a function
like image 66
HugeBelieve Avatar answered Jan 30 '26 08:01

HugeBelieve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!