In accordance with the specifications provided in §10.5, Chrome, or more specifically V8, adheres to what is explicitly stated.
var
Having multiple declarations of var x;
for the same symbol within the same scope does not have any impact, as the second declaration is essentially redundant. However, it's important to note that var x = 1;
(with an initializer) is interpreted as var x;
and then separately x = 1;
. In case of repetition, only the declaration part is disregarded, while the assignment remains effective.
For instance:
var x = 5;
var x;
console.log(x); // 5
var x = 42;
console.log(x); // 42
This code snippet effectively translates to:
var x;
x = 5;
console.log(x); // 5
x = 42;
console.log(x); // 42
Explore further: Poor misunderstood var
Function Declarations
In case of having multiple function declarations with the same name within the same scope, the last declaration takes precedence over the earlier ones.
foo(); // "foo the second!"
function foo() {
console.log("foo the first!");
}
function foo() {
console.log("foo the second!");
}
It's crucial to distinguish between function declarations and function expressions. The mentioned examples are declarations since the functions are defined without being immediately used in an expression context.
Function Expressions
Unlike function declarations, function expressions are executed when the step-by-step execution reaches them, similar to other expressions:
//foo(); // This would be an error
var foo = function() {
console.log("foo the first!");
};
foo(); // "foo the first!"
foo = function() {
console.log("foo the second!");
};
foo(); // "foo the second!"