javascript - Why defining function inside an if is a bad idea? -


from eloquent javascript marijn haverbeke

different javascript platforms in different browsers have traditionally done different things in situation, , latest standard forbids it.

but why bad?

function example () {     function () {} // okay     if ( ) {        function b () {} // danger !     } } 

it's considered "bad" because behavior inconsistent , doesn't people expect. consider following snippet:

if (true) {     function f() { return "t"; } } else {     function f() { return "f"; } } 

what calling f() return? on ie , firefox, return "t", on chrome , safari, return "f". why? combination of hoisting , javascript's scoping rules. information on how works, see this question on javascript scoping , hoisting.

effectively, means that, on browsers, branch ignored when comes function definitions using function name() { ... } form. if need (and don't, since poor style, anyway), use name = function () { ... } form instead, since not hoisted, behavior well-defined , not inconsistent across platforms.


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -