0

I just can't understand why the the a1 = function ?

and where is my value 1 that was passed to the fn(),

whether it was overrwrited by var a ?

the problem look like caused by the same names( var & function) !

function fn(a) {
    console.log("a1 = " + a);
    var a = 2;
    function a() { }
    console.log("a2 = " + a);
}
fn(1);
// a1 = function a() { }
// a2 = 2

function fnx(ax) {
    console.log("a1 = " + ax);
    var ax = 2;
    function b() { }
    console.log("a2 = " + ax);
}
fnx(1);
// a1 = 1
// a2 = 2

/* it equal to the final version */
function fn(a) {
    var a;
    a = function() { }
    // function hoisting > variable hoisting
    console.log("a1 = " + a);
    a = 2;
    console.log("a2 = " + a);
}
fn(1);
// a1 = function a() { }
// a2 = 2
xgqfrms
  • 10,077
  • 1
  • 69
  • 68

1 Answers1

1

I just can't understand why the the a1 = function ?

Function declarations are:

  1. Hoisted to the top of the function they appear in
  2. Declare a local variable (with the same name as the function) in the scope of the function they appear in (this isn't relevant because argument definitions do that too)
  3. Assign themselves as the value of that variable

and where is my value 1 that was passed to the fn(),

Overwritten by the function declaration

whether it was overrwrited by var a ?

The var is ignored because there is already a local variable named a.

The assignment overwrites the function between the two console.log statements.


Your code is effectively the same as:

function fn(a) {
    a = function a() { };
    console.log("a1 = " + a);
    a = 2;
    console.log("a2 = " + a);
}
fn(1);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335