In JavaScript, we can declare multiple variables either all at once or do it one line at a time. Here is the code for doing it all at once.

var someVariable1, someVariable2, someVariable3, someVariable4;

This way uses less code, but can be harder for some to read/maintain.

We prefer just putting one variable per line and keeping it simple.

var someVariable1;
var someVariable2;
var someVariable3;
var someVariable4;

You can see in this second way that there is more code and it takes up more space, but we find it much easier to read this way. Most examples on this site will have us declaring multiple variables this way.

Declaring and Intializing Multiple Variables in JavaScript

In the part above, we went over declaring multiple variables. But we can also initialize them by setting them to a particular value when we declare them.

We can also do this in the two ways we did above. The first way we will declare and initialize them all at once.

var someVariable1 = 1, someVariable2 = -2, someVariable3 = "This is some variable3", someVariable4 = true;

Once again, we prefer to do the declaring and initializing on separate lines to make it easier to read.

var someVariable1 = 1;
var someVariable2 = -2;
var someVariable3 = "This is some variable3";
var someVariable4 = true;

Hopefully this article has been useful in showing how to use JavaScript to declare multiple variables.

Categorized in:


Last Update: March 13, 2024