23

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?

Ezequiel Jadib
  • 14,767
  • 2
  • 38
  • 43
Robert Schillinger
  • 1,053
  • 3
  • 10
  • 15
  • Possible duplicate of [Declaring Multiple Variables in JavaScript](https://stackoverflow.com/questions/694102/declaring-multiple-variables-in-javascript) – gnzg Jan 30 '18 at 16:31

2 Answers2

33

"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.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • 4
    Not really a performance bottleneck, so much as saving time not having to type 'let' more than a handful of times. And I know it's basic javascript variable declaration, but was unaware if the syntax was the same in react native / jsx, and googling really didn't turn up much. – Robert Schillinger Dec 27 '16 at 20:03
  • 5
    That was a lot of extra for a very simple answer, don't you think? – Sean Lindo Jun 15 '18 at 17:10
  • @SeanLindo Oh yeah. And I could have done more. Not that I spend an inordinate amount of time thinking about syntax and code aesthetics and whatnot :D ... :/ ... :'( – Dave Newton Jun 24 '20 at 16:42
  • hi, may I ask why you don't declare variable like this anymore? – aanhlle Feb 24 '22 at 12:01
  • @aanhlle Just don’t; switched to multiple `let` statements. At the time I wrote this I was writing more Elixir than JS. – Dave Newton Feb 24 '22 at 13:57
18

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

Mayas
  • 1,434
  • 5
  • 16
  • 25
  • 5
    (I'm not convinced destructuring for destructuring's sake is the clearest code--it really separates the reference and its value and forces a fair amount of cognitive overhead if the number of refs is high.) – Dave Newton Dec 27 '16 at 20:32
  • IMHO the solution is not to avoid destructuring, but to avoid the high number of refs. However, this makes destructuring much less needed. – maaartinus Mar 03 '19 at 00:50