1

The code below will produce 8 due to the fact the second declaration will override the first one. Yup! Makes total sense.

EXAMPLE 1

function foo(){
    function bar() {
        return 3;
    }
    return bar();
    function bar() {
        return 8;
    }
}
console.log(foo()); // ---> 8

The following code produces 3 which means that it is the first expression that is invoked.

EXAMPLE 2

function foo(){
    var bar = function() {
        return 3;
    };
    return bar();
    var bar = function() {
        return 8;
    };
}
console.log(foo()); // ---> 3

I tend to conclude that in JavaScript, only the first declared variable is used as shown above. However, the code below produces 7 (hmmm... scratching my head)

EXAMPLE 3

var a = 4;
var a = 7;
console.log(a); //---> 7

Eventually, I will be using let or const (to prevent declaring the same variable many times) to declare variables and not var but I'm trying to understand why the results produced in example 2 and 3 are so unpredictable. Thanks.

lomse
  • 3,322
  • 6
  • 37
  • 62

2 Answers2

3

Example 1 is equivalent to the below code. Here bar is overridden before the return, so it is evaluated with the last value which is assigned to it. More about you can read Variable and Function Hoisting.

function foo(){
    function bar() {
        return 3;
    }
    
    function bar() {
        return 8;
    }
    
    return bar(); 
}
console.log(foo()); 

Example 2 is equivalent to the below code. Here you can see that bar is declared only once and the first value is assigned to it. The second assignment is done after the return, so the code does not reach to it. And the return is executed with the first assignment.

function foo(){
    var bar;
    bar = function() {
        return 3;
    };
    
    return bar();
    
    bar = function() {
        return 8;
    };
}
console.log(foo());

What about Example 3, when you declare the same variable many times with var, the later vars are just ignored. So like this

var a = 4;
a = 7;
console.log(a);
Suren Srapyan
  • 57,890
  • 10
  • 97
  • 101
1

No, it's just a difference how you declare the functions.

It's exactly the difference between var functionName = function() {} and function functionName() {}

Consider you have two functions.

var function1 = function() {

};
function function2() {

}

The difference is that function1 is a function expression and so only defined when that line is reached.

function1();
var function1 = function() {

};

When the compiler reaches this line will throw an error like function1 is not defined.

function2 is a function declaration and it's globally (due to hoisting).

function2();
function function2() {

}

This code will invoke the function2 function.

So, in your first example it's same like function2 (there is a function declaration).

In your second example it's same like function1 (there is a function expression)

Mihai Alexandru-Ionut
  • 41,021
  • 10
  • 77
  • 103