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.