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
.
This is perfectly legal - it simply defines the function within the if statement block.
In strict mode of ES5, function declarations cannot be nested inside of an if block 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.
The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.
For example, if the my_function() function, discussed in the previous section, requires two integer parameters, the declaration could be expressed as follows: return_type my_function(int x, y); where int x, y indicates that the function requires two parameters, both of which are integers.
When this question was asked, ECMAScript 5 (ES5) was prevalent. In strict mode of ES5, function declarations cannot be nested inside of an if
block 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 a
is only declared within the scope of if
statements and therefore doesn't exist in the global scope.
If you need to conditionally define a function, then you should use function expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With