Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter way to declare multiple variables in JavaScript?

Is there a faster/more efficient way of declaring multiple variables in react native? Instead of

let foo = 'foo';
let bar = 'bar';
let foobar = 'foobar';

Obviously not problem for three variables, but for bigger sets of variables, is there a better way?

like image 515
Robert Schillinger Avatar asked Dec 27 '16 19:12

Robert Schillinger


People also ask

Can we declare multiple variables at once in JavaScript?

You can declare multiple variables in a single line. However, there are more efficient ways to define numerous variables in JavaScript. First, define the variables' names and values separated by commas using just one variable keyword from var , let or const.

What are the 4 ways to declare a JavaScript variable?

4 Ways to Declare a JavaScript Variable: Using var. Using let. Using const. Using nothing.

Can I declare multiple variables in single line?

Do not declare more than one variable per declaration. Every declaration should be for a single variable, on its own line, with an explanatory comment about the role of the variable. Declaring multiple variables in a single declaration can cause confusion regarding the types of the variables and their initial values.


2 Answers

"Faster"? You've determined there's a performance bottleneck here?!

In any case, you can declare multiple variables:

let foo    = 'foo'
  , bar    = 'bar'
  , foobar = 'foobar'
  ;

But this is simply JS syntax–is this what you are really asking?

If you have a "large" number of related variables the problem may be more systemic, and there are multiple types of refactorings that might help.

Updated: I used to declare variables like this; I don't anymore.

like image 67
Dave Newton Avatar answered Sep 26 '22 06:09

Dave Newton


This is more of a general JS syntax question.

Depending on your use case, you can just destructure an array as such:

const [ foo, bar, foobar ] = [ 'foo', 'bar', 'foobar' ]

Note that these are constants, having a lot of variables in a scope makes it poorly readable. See here for more

like image 33
Mayas Avatar answered Sep 26 '22 06:09

Mayas