javascriptfunctiondeclaration

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!


Solution

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