Shivam
Shivam

Reputation: 411

Why console output is coming as a function?

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

Upvotes: 1

Views: 87

Answers (2)

impregnable fiend
impregnable fiend

Reputation: 289

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.

Upvotes: 0

Jarek Kulikowski
Jarek Kulikowski

Reputation: 1389

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.

Upvotes: 1

Related Questions