Samul
Samul

Reputation: 2019

Why does a function declared inside a conditionally-executed block appear to exist before the block is entered?

I spent the last 3 days trying to minify a problem and now that I discovered it I cannot understand.

I want to check if a function exists, if not then create it. However the JS always says the function exists even before it start existing.

Check:

if (!blablabla) {
  function blablabla() {
    //do stuff
  }

  console.log("1");
} else {
  console.log("2");
}

It should display 1 but it always shows 2!

Upvotes: 0

Views: 71

Answers (3)

RobG
RobG

Reputation: 147363

ECMA-262 may appear to not allow conditional function declarations, however there is a loophole that permits them. In most browsers the following will print "bar!!" but in Firefox it will throw a reference error since bar has not been defined.

function foo() {

  if (!bar) {
    console.log('no bar');
    function bar(){}

  } else {
    console.log('bar!!');
  }
}

foo()

To avoid the reference error, you can use:

  if (typeof bar == 'undefined')

however it's not a good idea to use conditional declarations due to the different behaviour in different browsers. A function expression can be used instead:

if (typeof bar == 'undefined') {
  bar = function(){};
}

that will conditionally create a global bar function in all browsers. A variable declaration will create the function only in the current execution context

if (typeof bar == 'undefined') {
  var bar = function(){};
}

Upvotes: 3

MT0
MT0

Reputation: 167867

if ( typeof blablabla !== 'function' ) {
    blablabla = function() {
        //do stuff
    };
    alert("1");
}
else
{
    alert("2");
}

Upvotes: 0

Guffa
Guffa

Reputation: 700212

That's because the function always exists.

When you declare a function, it exists in the entire scope from when the code starts to run. The function declaration is hoisted to the scope level, so it doesn't matter if you declare it inside the if statement or outside it.

If you want to create a function at runtime, you have to create it as a function expression, and assign it to a variable:

if (!blablabla) {

    blablabla = function() {

        //do stuff

    };

    alert("1");

}
else{

    alert("2");

}

Upvotes: 4

Related Questions