3

Is there a difference in terms of performance between:

Example 1:

function abc(x,y){
  return x + y;
}

abc();

Example 2:

abc();

function abc(x,y){
  return x + y;
}

Example 3:

var abc = function(x,y){
  return x + y;
}

abc();

Which is better and what are the pros and cons of each?

Andrew Li
  • 47,104
  • 10
  • 106
  • 132
yqlim
  • 5,648
  • 3
  • 15
  • 36
  • 2
    no difference at all. Just different style of writing them. Once compiled by javascript engine they all are same. If you don't pass any parameters then also you don't get any runtime exception until and unless function implementation is exact similar to above one. – vijayP Nov 03 '16 at 04:19
  • 2
    Well, there is a difference, syntactically. Example 3 is a function *expression*, see [here](http://stackoverflow.com/q/261599/5647260). Performance wise, I don't think so. Even if there was, it would be pretty tiny. – Andrew Li Nov 03 '16 at 04:23
  • 1
    It's extremely unlikely that there is any performance difference between 1 and 2 since all code is first parsed, then function declarations are processed before any execution begins. There might be a slight penalty with 3 since the function body will not be evaluated until it is reached during execution, but I doubt it's significant. – RobG Nov 03 '16 at 04:56
  • try AST Explorer: https://astexplorer.net/ . Basically JS engines parse all your above code in same way before execution. So don't worry about the performance. Its just the style you write. AST- abstract syntax tree which is a level of parsing your code and constructing our code in hand before execution. – Nirus Nov 03 '16 at 05:57

2 Answers2

1

There are two Stage of javascript execution, 1) Creation Stage 2) Execution Stage

Creation Stage : In creation stage all the variable and function are created with a value undefined in case of variable for eg in your second case

abc();

function abc(x,y){
  return x + y;
}

Here function abc() is defined in its creation stage,so even though you called it first it will not give you any error. Because abc() it is called during its execution stage As you are not passing any variable to function x and y will be undefined in this case

Execution Stage : In execution stage function abc is called which was defined during its creation stage.So no matter wherever you call a function you will never get an error.

Javascript is synchronous

One very important thing in javascript is LEXICAL ENVIRONMENT ie where your function or variable sits.in which lexical environement.

Parshuram Kalvikatte
  • 1,524
  • 2
  • 15
  • 38
0

i think performance wise there is no difference ..syntax wise there is difference

jitendra varshney
  • 3,262
  • 1
  • 17
  • 25