javascript - Hoisting of functions inside conditionals -
i understanding how hoisting in javascript occurs, functions hoisted before variables, , declarations hoisted. when came across hoisting inside if/else conditionals, one:
foo(); // "b output" var = true; if (a) { function foo() { console.log("a"); } } else { function foo() { console.log("b"); } } now conditional true, according if block, a should have been output, due kind of hoisting assume b output.
so how b output?
(ignoring dodgy behaviour old browsers may have had:)
in javascript, function statements scoped within containing function (or globally if there no containing function), they're not scoped within if or else or loop block. can't declare function conditionally in manner (it can done way; see below). , if declare more 1 function same name in same scope later 1 overwrite first one.
so happens code is:
both function statements hoisted, but
they both have same name first overwritten second.
the variable,
acreated not yet assigned value.the
foo()statement executed, logging "b"aassigned valuetrue.the if executed. condition true, neither if nor else branches because don't contain statements other function declarations hoisted earlier.
if want create functions conditionally have declare variable , assign function expression it. , can not call function until after assignment:
var foo; var = true; if(a) foo = function() { console.log("a"); }; else foo = function() { console.log("b"); }; foo();
Comments
Post a Comment