1
var a=10;
if(a===10){
  console.log(a);
  function a (){}
  console.log(a);
}

Since, if condition is true then why value of both console.log is coming as function in chrome v58 and coming as 10 in IE 8? Please refer to the screenshot of Chrome and IE8 console output.

Chrome:

enter image description here

IE 8:

enter image description here

Shivam
  • 411
  • 4
  • 6

2 Answers2

1

Look up function hoisting as suggested by @impregnable fiend. In your code, even though you declare a=10; Javascript will scan all the code and pull all defined functions it finds before doing anything else. So, it will find function function a() {} and will overwrite a=10 before console.log is called.

Jarek Kulikowski
  • 1,399
  • 8
  • 9
0

Your code is equivalent to this code:

var a = 10;
if (a===10) {
  var a = function() {};
  console.log(a);
  console.log(a);
}

First of all 'var' and 'function' goes to the beginning of the scope. Read about scopes and, particularly, hoisting.

impregnable fiend
  • 289
  • 1
  • 5
  • 16
  • 1
    This isn't actually correct. Hoisting is involved, but your variant of the code hoists the function definition to above `var a = 10;`. So your code will print `10\n10` whereas OP's code prints `function a(){}\nfunction a(){}`. – Adaline Simonian Jul 29 '17 at 18:55
  • @VartanChristopherSimonian okay, thx that you've noticed my error :) Am I correct now? In that instance. – impregnable fiend Jul 29 '17 at 19:50
  • Kind-of. Per ECMA-262, [Blocks can only contain Statements](https://tc39.github.io/ecma262/#sec-block), and a FunctionDeclaration is not a Statement. ECMAScript 5 even explicitly said that [use of FunctionDeclarations as Statements is discouraged](https://es5.github.io/x12.html#x12). So the hoisting behaviour, from what I understand, for a function defined in a block is undefined. Node just happens to hoist the function to the top of the block. [Here's a case where SpiderMonkey wouldn't hoist any functions defined in a block.](http://statichtml.com/2011/spidermonkey-function-hoisting.html) – Adaline Simonian Jul 29 '17 at 20:05