Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function declarations inside if/else statements?

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.

like image 737
HellaMad Avatar asked Apr 09 '12 05:04

HellaMad


People also ask

Can you put a function inside an IF statement?

This is perfectly legal - it simply defines the function within the if statement block.

Can we write function inside if statement in JavaScript?

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.

Can we use if else in functions?

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.

What is function declaration example?

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.


1 Answers

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.

like image 50
Cheran Shunmugavel Avatar answered Oct 09 '22 16:10

Cheran Shunmugavel