Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created June 20, 2012 18:24
Show Gist options
  • Save cowboy/2961408 to your computer and use it in GitHub Desktop.
Save cowboy/2961408 to your computer and use it in GitHub Desktop.
javascript: function declaration vs expression
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
Copy link

just for curiosity:

function foo(state) {
  console.log(bar); // raises an error: bar is not defined
  return state ? function bar() { return 1; } : null;
}

function foo(state) {
  console.log(bar); // bar()
  function bar() { return 1; }
  return state ? bar : null;
}

Not that a function declaration could be great inside a ternary.

@cowboy
Copy link
Author

cowboy commented Jun 21, 2012

@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."

@leobalter
Copy link

Thanks. \o/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment