Is it good to declare one variable per var statement, it makes code easier to re-order the lines in the program as per modification needs.
Could somebody make out, is there any difference between following style of declarations in Node.js in terms of execution of code?
//Style 1
var keys = ['foo', 'bar']; var values = [23, 42];
//Style 2
var keys = ['foo', 'bar'], values = [23, 42];
You can have multiple var statements in JavaScript; this is called hoisting; However, because you can run into scoping issues, it's best to use a single declaration in any function.
It's common to see this style
var keys = ['foo', 'bar'],
values = [23, 42];
In fact, the very reason JavaScript allows you to chain the declarations together is because they should be happening together.
To illustrate a scoping issue:
f = "check?";
var hello = function () {
console.log(f); // undefined
var f = "nope!";
console.log(f); // nope!
};
var hello2 = function () {
console.log(f); // check?
var f2 = "nope!"; // not reusing `f` this time
console.log(f2); // nope!
};
hello();
hello2();
At first glance, you'd think the first output would be check?, but because you're using var f inside the function body, JavaScript is creating a local scope for it.
To avoid running into issues like this, I simply use a single var declaration :)