-
-
Save cowboy/2961408 to your computer and use it in GitHub Desktop.
function foo(state) { | |
function bar() { return 1; } | |
return state ? bar : null; | |
} | |
foo(false) // null (bar is created but not used) | |
foo(true)() // 1 (bar is created and returned) | |
function foo(state) { | |
return state ? function() { return 1; } : null; | |
} | |
foo(false) // null (the anonymous function isn't even created) | |
foo(true)() // 1 (the anonymous function is created and returned) |
@leobalter, in your first example, not only is the function expression not created until after the console.log
(and only if state
is truthy) but the name bar
will actually only be accessible inside of function bar
and not outside. Unless you're in IE JScript, where named function expression names leak. When using a function declaration however, the function name is available both inside and outside the function.
Also, just arguing semantics for a moment, statements can't be operands of the conditional (aka ternary) operator, only expressions. That means that, because a function declaration is a statement, your statementº is invalid. Now, a function expression, on the other hand, can be the operand of a conditional operator. Not that it would be great there :)
º literary statement, not computer programming statement, eg. "Not that a function declaration could be great inside a ternary."
Thanks. \o/
just for curiosity:
Not that a function declaration could be great inside a ternary.