0

console.log(aName);
var aName = 'Martin';

I tried to execute this JS code in latest Google chrome and Edge browsers. It printed name value. i.e. 'Martin'. I got little confused here, because of JavaScript hoisting. According to hoisting only declarations are hoisted and not initialization. Since it is 'var', it should throw undefined error as per my assumption. But, when I tried with IE-11 browser, it worked as expected and threw undefined error. What is going here?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • It's called [hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) and it's been doing this in all browsers since, well forever – Liam Jan 07 '21 at 17:05
  • You sure about that? Just tried it in chrome console and it printed `undefined` as expected. Of course, if you execute this snippet again in the same console, it will print `Martin`, as the assignment is still valid. – derpirscher Jan 07 '21 at 17:06
  • Just plugged your code example into Chrome console and got "undefined" - Version 87.0.4280.88 (Official Build) (64-bit) – Ryan Wilson Jan 07 '21 at 17:06
  • Are you sure you're not running the snippet twice? – This company is turning evil. Jan 07 '21 at 17:08
  • I created a fiddle and it produces "undefined" - (https://jsfiddle.net/8phao6dy/) – Ryan Wilson Jan 07 '21 at 17:10
  • `name` may be `window.name` and already initialised. I made you a snippet with `aName` instead – mplungjan Jan 07 '21 at 17:15
  • 1
    Thanks to all of your commented answers here. Yes, I think, I have probably executed the script twice in the same console. That's why, it was giving weird, unexpected answer. – Sadashiv J P Jan 08 '21 at 07:23

0 Answers0