Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring multiple variables in JavaScript

In JavaScript, it is possible to declare multiple variables like this:

var variable1 = "Hello, World!"; var variable2 = "Testing..."; var variable3 = 42; 

...or like this:

var variable1 = "Hello, World!",     variable2 = "Testing...",     variable3 = 42; 

Is one method better/faster than the other?

like image 405
Steve Harrison Avatar asked Mar 29 '09 04:03

Steve Harrison


People also ask

Can I declare multiple variables JavaScript?

Declare Multiple Variables in JavaScript Copy var cost = 25; const name = "Onion"; let currency = "NPR"; However, there are shorter ways to declare multiple variables in JavaScript. First, you can only use one variable keyword ( var , let , or const ) and declare variable names and values separated by commas.

How do you declare multiple variables?

If your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.

Can I declare multiple variables in single line?

Declaring multiple variables in a single declaration can cause confusion regarding the types of the variables and their initial values. If more than one variable is declared in a declaration, care must be taken that the type and initialized value of the variable are handled correctly.

How set multiple values in JavaScript?

To assign multiple variables to the same value with JavaScript, we can use the destructuring syntax. For instance, we can write: const [ moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown ] = Array(6). fill(false); console.


1 Answers

The first way is easier to maintain. Each declaration is a single statement on a single line, so you can easily add, remove, and reorder the declarations.

With the second way, it is annoying to remove the first or last declaration because they start from the var keyword and finish with the semicolon respectively. Every time you add a new declaration, you have to replace the semicolon in the last old line with a comma.

like image 86
Paige Ruten Avatar answered Oct 13 '22 23:10

Paige Ruten