简体   繁体   中英

How is hoisting applied to this JavaScript code?

I know this code prints 2 because of varibale hoisting but I do not fully understand how.

I'm going to list everything that I understand and would be very grateful if you could answer with true or false next to each one. You can then add any additional information.

1) The line let b = innerMagic() references the innerMagic() function, which returns a;

2) We have now assigned the value 3 to the variable a, which means return b, should return 3. However at the moment the variable is set to 2, so it returns 2. You can not call a variable before a variable before it has been assigned.

 function magic() { let a = 1; a = 2; let b = innerMagic(); a = 3; return b; function innerMagic() { return a; } } console.log(magic()) 

innerMagic takes the value of a from the outside scope at the time when it's called. So when innerMagic is called, a has the value 2. It returns this value (2), to b, and you return b (2), and that's what you print

"let b = innerMagic() references the innerMagic() function, which returns a;" that's not quite right, it returns the value of a ie 2.

At this point both a and b hold the value 2. a is then updated to the value 3 but b still has the value 2.

For an explanation of value vs reference take a look at this article on Explaining Value vs. Reference in Javascript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM