-1

One of my colleagues suggested me to declare variables on the top of file like

var a,b,c,d;
// or
var a=1,b=1,c=1,d=1;

instead of

var a=1;
//some code
var b =1;
//some code
var c=1;
//some code
var d=1;

saying that it impacts JS performance.

Does it really make any difference?

writeToBhuwan
  • 3,233
  • 11
  • 39
  • 67
  • If it does make a difference, it's on the order of microseconds - if even that, possibly even nanoseconds. – Niet the Dark Absol Jul 24 '17 at 09:12
  • See [this question](https://stackoverflow.com/questions/9746359/javascript-code-conventions-variable-declaration) also . – Phylogenesis Jul 24 '17 at 09:13
  • Possible duplicate of [JavaScript code conventions - variable declaration](https://stackoverflow.com/questions/9746359/javascript-code-conventions-variable-declaration) – cнŝdk Jul 24 '17 at 09:14
  • 1
    Fixed the typo sir – writeToBhuwan Jul 24 '17 at 09:17
  • Why the downvotes? Was it such a stupid question? – writeToBhuwan Jul 24 '17 at 09:19
  • Did you try it and see? – xaxxon Jul 24 '17 at 11:01
  • @writeToBhuwan: (I don't understand the downvotes either.) You may find [this answer](https://stackoverflow.com/questions/35597969/what-is-the-purpose-of-let-hoisting-in-es6) useful in understanding at a deeper level what's going on in that code. – T.J. Crowder Jul 24 '17 at 11:24
  • @T.J.Crowder I downvoted because no effort was put into finding the answer out for himself. Also because the question is insufficient for anyone else to answer because it doesn't have enough information to determine what may or may not be faster for this person's specific setup. – xaxxon Jul 25 '17 at 05:48

1 Answers1

5

No, it makes no difference whatsoever in terms of performance. Regardless of where the var is, those declarations are all processed upon entry to the function ("var hoisting"), before any step-by-step code execution occurs. I mean, there might or might not be some truly infinitessimal parsing benefit, but even if there is, it's not going to be anything you're going to see in real life.

Collecting all the vars at the top does make the code more accurately reflect the reality of when those variables are created (again because of var hoisting). But if the code is long enough that that's an issue, it needs to be broken into smaller functions anyway. :-)

xaxxon
  • 19,189
  • 5
  • 50
  • 80
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875