Search code examples
javascriptfunctionecmascript-5javascript-function-declaration

Function declaration vs expression from a performance point of view?


There's many javascript articles on the web comparing function declarations function foo (){} to function expressions var foo = function () {}. They usually mention things like hoisting, behaviour within conditionals, etc... But I don't recall any of them talking about performance. Is there any difference? Particularily in ECMA5's strict-mode (if that changes anything).

By performance I of course mean execution performance (including lookup, scope traversal, etc..) not declaration performance, although that would be a nice-to-know aswell.


Solution

  • Function declarations are faster in cases where there's a potential for the function expression to be evaluated multiple times. For example, in code that is called in a loop a hoisted function is only evaluated once, but an expression would be evaluated each time. Besides that, there's no meaningful difference.

    Whenever you have a question about a JavaScript performance issue, I recommend checking out JSPerf. Also, Google to see if someone already made one for your question: