7

What purpose does name have in the following statement?

var myArray =[], name;

I usually initialize my arrays as the following:

var myArray =[];
burnt1ce
  • 12,985
  • 28
  • 96
  • 146

8 Answers8

18

It is shorthand to

var myArray =[];
var name;

It is matter of personal preference.

Community
  • 1
  • 1
amit_g
  • 28,825
  • 7
  • 54
  • 111
11

You are actually initialising two variables there, myArray and name.

You set myArray to [] and name to undefined, because you don't give any value.

Your code is equivalent to this:

var myArray = [];
var name;
lonesomeday
  • 215,182
  • 48
  • 300
  • 305
8

It is equal to this:

var myArray =[];
var name;
aorcsik
  • 13,773
  • 4
  • 37
  • 48
8

In JavaScript multiple variable assignments can be separated by commas, eliminating the need for repetitive var statements.

var myArray = [];
var name;

is equivalent to

var myArray = [], name;
g.d.d.c
  • 41,737
  • 8
  • 91
  • 106
7

This is equivalent to

var myArray =[];
var name;
trutheality
  • 21,548
  • 6
  • 47
  • 65
7

It doesn't affect myArray, it's just the same thing as

var myArray = [];
var name;
brymck
  • 7,216
  • 25
  • 30
4

It's essentially the instantiation of a second variable name with no value.

ShaneBlake
  • 10,706
  • 2
  • 23
  • 42
1

The recommended way (clean and short as possible) of writing this kind of code is the following:

var myArray = [],
    name;
antonjs
  • 13,120
  • 11
  • 61
  • 86