1

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];
1
  • 3
    They are equivalent but the second has less typing (don't have to type var over and over). Helpful for a block of variables. Commented Feb 11, 2013 at 13:26

1 Answer 1

4

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 :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.