Function declarations inside if/else statements?

JavascriptFunctionScope

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

From http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

In javascript, you have function declaration:

function foo() {
}

and function expression

var foo = function() {
}

Quoting from http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

> “Function declarations and function variables are always moved > (‘hoisted’) to the top of their JavaScript scope by the JavaScript > interpreter”.

So what happened in your first example is that function declaration of function a(), gets hoisted to the top of the Javascript scope, thus producing 'foo' even though the if evaluates to false

Think of var foo as a normal Javascript statement, it's only executed on the runtime of your javascript, unlike function foo(), that's why the below is valid:

alert(foo());

function foo() {
   return 'gw ganteng';
}

Here, function foo() is parsed by the parser, putting foo() in the current scope, before attempting to call alert(foo())

http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/ > In JavaScript execution there is Context (which ECMA 5 breaks into > LexicalEnvironment, VariableEnvironment and ThisBinding) and Process > (a set of statements to be invoked in sequence). Declarations > contribute to the VariableEnvironment when the execution scope is > entered. They are distinct from Statements (such as return) and are > not subject to their rules of process.

Solution 3 - Javascript

The ECMA-262 v5 requires implementations to register all function and variable declarations during the first pass when entering any new global or function-level execution context. Chrome is technically doing it right here because it is looking inside the else and then blocks and registering a() prior to execution. Unfortunately it produces the most unreadable results.

FF is waiting until it evaluates the if statement before it evaluates and adds function and variable declarations to the current context. BTW. Both browsers do it this way inside catch and finally clauses.

It really is just a matter of two different ECMA implementations dealing with a feature that shouldn't be there to begin with. The scenario at hand shows why function declarations shouldn't be inside control flow statements.

Solution 4 - Javascript

Function declarations are not accessible outside {} blocks.
if (true) {
  function sayHi() {
    alert("hii");
  }
  sayHi(); //accessible
}

sayHi(); //error, not accessible since out of the block
If you want to define conditional functions, use function expressions like
let sayHi;
if (true) {
  sayHi = function(){
    alert("hii");
  }
  sayHi(); //accessible
}

sayHi(); //accessible

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHellaMadView Question on Stackoverflow
Solution 1 - JavascriptCheran ShunmugavelView Answer on Stackoverflow
Solution 2 - JavascriptAndreas WongView Answer on Stackoverflow
Solution 3 - Javascriptdrankin2112View Answer on Stackoverflow
Solution 4 - JavascriptNitin JadhavView Answer on Stackoverflow