-1

Sometimes it happens that there are 50k + lines in the code and they should be optimized to make it work faster. Here I have such a question about functions. We know difference between:

function f () {
  //code here
}

and

var f = function () {
  //code here
}

first is instant declared when code loads and second is declared in the process of going through the code. It means that:

f();
var f = function () {
  //code here
}

this will throw an error. However:

f();
function f () {
  //code here
}

this will work fine.

My question is this. Is there any fundamental difference between those two declarations. Can it affect the performance of such big projects where code lines are above 50k?

Deepesh kumar Gupta
  • 884
  • 2
  • 11
  • 29
KoboldMines
  • 428
  • 2
  • 6
  • 21
  • 1
    This is not really a question for Stackoverflow - you could do some matching and tests yourself on something like https://jsperf.com/ – StudioTime Sep 06 '18 at 06:08
  • This you can find by simple googling. – Deepesh kumar Gupta Sep 06 '18 at 06:11
  • Simple googling will indeed answer that question, even on SO: [Javascript: performance of var functionName = function() {} vs function functionName() {}](https://stackoverflow.com/questions/4751178/javascript-performance-of-var-functionname-function-vs-function-function). For a real deep dive: [var functionName = function() {} vs function functionName() {}](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname?rq=1) – Malte Hartwig Sep 06 '18 at 06:12

3 Answers3

1

actually there is some difference http://jsben.ch/SqczP

Branch with variable-based declaration demonstrates 11% better performance.

But actual answer to your question: no, it will not until you decide to declare functions in large loop. and even then you have stop doing such a structure instead of optimizing declaration

skyboyer
  • 22,209
  • 7
  • 57
  • 64
0

Function declarations in JavaScript are hoisted to the top of the enclosing function or global scope. You can use the function before you declared it:

Function declarations load before any code is executed.

hoisted(); // logs "foo"

function hoisted() { console.log('foo'); }

AND

Note that function expressions are not hoisted (you cannot call before):

Function expressions load only when the interpreter reaches that line of code.

notHoisted(); // TypeError: notHoisted is not a function

var notHoisted = function () { console.log('bar'); };

agravat.in
  • 561
  • 6
  • 14
0
f();
var f = function () {
  //code here
}

This won't work because the declaration if hoisted but the assignment isn't, it actually runs like this

var f;
f();
f = function () {
  //code here
}
Chris Li
  • 2,628
  • 1
  • 8
  • 23