Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: performance of var functionName = function() {} vs function functionName() {} [duplicate]

Tags:

javascript

Possible Duplicate:
Does use of anonymous functions affect performance?

What are performance implications (if any) on parse and run-time when using function expression vs declaration in Javascript?

For example, what are performance characteristics and differences of the following two ways:

var functionOne = function() {
    // Some code
}

or:

function functionTwo() {
    // Some code
}

NOTE: The question is not about whether it is faster to declare function but about function execution.

like image 278
user148273 Avatar asked Jan 20 '11 18:01

user148273


People also ask

What is VAR function in JavaScript?

The var statement declares a variable. Variables are containers for storing information. Creating a variable in JavaScript is called "declaring" a variable: var carName; After the declaration, the variable is empty (it has no value).

Can we use a function as a variable value in JavaScript?

Programmers can create a single variable using the var, let, or const keywords and assign the function expression to that. However, creating a variable with the const keyword is recommended to assign the function as the function expression always remains constant.

Which keyword is most commonly used to define a function in JavaScript?

JavaScript functions are defined with the function keyword. You can use a function declaration or a function expression.


2 Answers

Much more important than performance differences are the semantic differences between those two.

  • A function declared with a function declaration statement (second sample) has a name that will show up in stack traces etc.
  • Function declaration statements are "hoisted" to the top of their blocks and interpreted as if they actually appeared there, before any other statements in the function run.

The performance differences are probably pretty tiny, if even detectable, at least in modern runtime environments.

like image 195
Pointy Avatar answered Oct 01 '22 06:10

Pointy


Here is a JSPerf Link, try testing on multiple browser, because results tend to vary. In chrome 10 the function statement got better score. http://jsperf.com/fn-expression-vs-statement

like image 39
Amjad Masad Avatar answered Oct 01 '22 06:10

Amjad Masad