When I read javascript code that is clean and written by people who are obviously very good at it, I often see this pattern
var x = some.initialization.method(),
y = something.els(),
z;
What is the advantage of that over writing
var x = some.initialization.method();
var y = something.els();
var z;
The second format is easier to maintain, since each line exists by itself. So you can erase a line or add a line, and not have to look around to see if it's the first or last variable to be initialized. This also means source control diffs/merges will work better. Given these disadvantages, I'm guessing there's some advantage to the first format -- but what is it? Surely they execute identically because it's the same to the parser.
Initializing a variable as Telastyn pointed out can prevent bugs. If the variable is a reference type, initializing it can prevent null reference errors down the line. A variable of any type that has a non null default will take up some memory to store the default value.
The var keyword is used to declare variables in JavaScript. Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows. Storing a value in a variable is called variable initialization.
Always declare JavaScript variables with var , let , or const . The var keyword is used in all JavaScript code from 1995 to 2015. The let and const keywords were added to JavaScript in 2015. If you want your code to run in older browser, you must use var .
You can declare multiple variables in a single line. However, there are more efficient ways to define numerous variables in JavaScript. First, define the variables' names and values separated by commas using just one variable keyword from var , let or const.
There's a slight advantage with the size of the javascript that is sent to the browser; Google's Closure compiler in 'whitespace only' mode will compile the single var version into:
var x=some.initialization.method(),y=something.els(),z;
and the multi as:
var x=some.initialization.method();var y=something.els();var z;
I changed your else
to els
so that it would compile.
This isn't a massive gain (especially if you are also compressing the files), and the 'simple' compilation mode will do this for you anyway, so I probably wouldn't be too concerned about it unless you can find more compelling reasons.
One reason you may not want to do this is that if you accidentally use a semicolon instead of a comma you've just found a global.
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