Should I declare JavaScript variables and then initialize right after?

I'm new to JavaScript, and I was wondering if declaring variables, and then initializing right after the declaration, is best practice. For instance:

var x = 5 ; var y = 6 ; 

Instead:

 var x , y ; x = 5; y = 6 ; 
+5
source share
2 answers

How this is done does not affect execution in any way, and it's just a matter of readability.

If you have a preference for announcing, then assign separately, no matter what.

If you do not use local scope variables such as var banana , as in classes, there is an effect on execution (but hardly).

example: this is probably easier to read (but this is a personal opinion) and requires less operation

 var Foo = Class.reate(); Foo.prototype = { hoge : 1, fuga : 2, initialize : function(){ } }; 

than that:

 var Foo = Class.reate(); Foo.prototype = { hoge:null, fuga:null, initialize : function(){ this.hoge = 1; this.fuga = 2; } }; 
+1
source

How you actually declare variables is a matter of preference. If you declare several variables one after another, you can omit the var keyword and instead use commas to continue the statement.

 var x = 2, y = 3; 

If I use one variable when assigning another, I like to split declaration and assignment for readability.

 var x = 2, y = x + 3; 

against

 var x, y; x = 2; y = x + 3; 

Again, this is only preference, since any variable in javascript can be used as soon as it is declared - even in the same var expression.

It is important to remember that variables in javascript have a function area - not a block area commonly found in other languages โ€‹โ€‹(well, as long as ES6 javascript is available).

 (function(){ var x = 1; for (var i = 0; i < 10; i++) { var x = i; } (function(){ var x = 999; }()); alert(x); // 9! }()); 

Javascript guru Douglas Crockford recommends that variable definitions be listed at the top of each function to make it more obvious to programmers used for languages โ€‹โ€‹with the correct block area.

+3
source

All Articles