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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With