Is hoisting really necessary in javascript to enable mutual recursion? -


in online course, kyle simpson says following code demonstrates necessity of hoisting in javascript, because without hoisting "one of functions declared late."

a(1)  // 39  function a(foo){   if (foo > 20) return foo     return b(foo+2) }  function b(foo){   return c(foo) + 1 }  function c(foo){   return a(foo*2) } 

but works fine.

var = function(foo){   if (foo > 20) return foo     return b(foo+2) }  var b = function(foo){   return c(foo) + 1 }  var c = function(foo){   return a(foo*2) }  a(1) // 39 

so what's story? convenience , placement of invocation aside, there situations require hoisting?

the claim i've made non-hoisted js being unable support mutual recursion conjecture illustration purposes. it's designed understand need language know variables available in scope(s). it's not prescription exact language behavior.

a language feature hoisting -- hoisting doesn't exist, it's metaphor variables being declared in scope environments ahead of time during compilation, before execution -- such fundamental characteristic can't reasoned when separated rest of language's characteristics.

morever, impossible test hypothesis in js. snippet in op deals part of equation, uses function expressions instead of function declarations avoid function hoisting.

the language using compare illustration c, example requires function signatures declared in .h header files compiler knows function looks if hasn't "seen" yet. without it, compiler chokes. that's sort of manual hoisting in sense. c type checking, 1 can imagine sort of requirement existing other reasons that.


another way of thinking whether js compiled language has been discovered before executes, or whether interpreted top-down in single pass.

if js top-down interpreted, , got definition of a() function referenced b() inside it hadn't seen yet, problem. if call expression handled non-lazy, engine couldn't figure out @ moment b() call about, because b() hadn't been processed yet. languages lazy , non-lazy.

as is, js compiled first before execution, engine has discovered functions (aka "hoisting") before running of them. js treats expressions lazy, explains why mutual recursion works fine.

but if js had no hoisting and/or not lazy, 1 can imagine js engine unable handle mutual recursion because circular reference between a() , b() in fact mean 1 of 2 declared "too late".

that's meant in book.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -