How are function declarations handled?
var abc = '';
if (1 === 0) {
function a() {
abc = 7;
}
} else if ('a' === 'a') {
function a() {
abc = 19;
}
} else if ('foo' === 'bar') {
function a() {
abc = 'foo';
}
}
a();
document.write(abc); //writes "foo" even though 'foo' !== 'bar'
This example produces different outputs in Chrome and Firefox. Chrome outputs foo while FF outputs 19.
When this question was asked, ECMAScript 5 (ES5) was prevalent. In strict mode of ES5, function declarations cannot be nested inside of an
ifblock as shown in the question. In non-strict mode, the results were unpredictable. Different browsers and engines implemented their own rules for how they would handle function declarations inside blocks.As of 2018, many browsers support ECMAScript 2015 (ES2015) to the extent that function declarations are now allowed inside blocks. In an ES2015 environment, a function declaration inside of a block will be scoped inside that block. The code in the question will result in an undefined function error because the function
ais only declared within the scope ofifstatements and therefore doesn’t exist in the global scope.If you need to conditionally define a function, then you should use function expressions.