Im new to JavaScript and I was wondering if declaring variables and then initializing right after declaration is a best practice. For example:
var x = 5 ;
var y = 6 ;
Instead of:
var x , y ;
x = 5;
y = 6 ;
How you actually declare variables is a matter of preference.
If you declare multiple variables after each other you can omit the var
keyword and instead use commas to "continue" the statement.
var x = 2,
y = 3;
If I am using one variable in the assignment of another I like to split the declaration and assignment for readability.
var x = 2,
y = x + 3;
var x, y;
x = 2;
y = x + 3;
Again this is only a preference since any variable in javascript is usable as soon as it is declared
var
statement.Its important to remember that variables in javascript have function scope - not block scope as commonly encountered in other languages.
(function(){
var x = 1;
for (var i = 0; i < 10; i++) {
var x = i;
}
(function(){
var x = 999;
}());
alert(x); // 9!
}());
The javascript guru Douglas Crockford recommends that variable definitions be listed at the top of each function to make this extra apparent to programmers used to languages with proper block scope.
Update:
The use of var
is not recommended in modern javascript. let
and const
are supported by all modern browsers and they have true block scope and are not hoisted to the top of a function.
How this is done does not affect execution in any way, and is merely a question regarding readability.
If it has your preference to declare, then assign separately, by all means do so.
If you are not using local scope variables like var banana
, like in classes, there is some effect on execution (but barely).
example : this is probably easier to read, (but that is a personal opinion) and requires less operations
var Foo = Class.reate();
Foo.prototype = {
hoge : 1,
fuga : 2,
initialize : function(){
}
};
than this :
var Foo = Class.reate();
Foo.prototype = {
hoge:null,
fuga:null,
initialize : function(){
this.hoge = 1;
this.fuga = 2;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With