2

I'm wondering if JavaScript allows multiple addition-assignment operators in one statement. I know about multiple variable assignment, discussed here.

My current way of coding looks somewhat like this:

var x = someComplicatedFunction();
foo += x;
bar += x;

Is there a way to do something like this?

foo, bar += someComplicatedFunction();
Community
  • 1
  • 1
Jared Nielsen
  • 3,669
  • 9
  • 25
  • 36

1 Answers1

2

You can put as many statements as you want in one line :

var x = someComplicatedFunction(); foo += x; bar += x;

If you want to do everything in one statement, it's more messy but it's doable :

bar -= foo - (foo += someComplicatedFunction());

But there's nothing magical letting you do everything in one statement without assignation and being readable.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 3
    The second statement is very clever, albeit at the expense of readability. I was wondering if JavaScript had some syntactic sugar I wasn't aware of. – Jared Nielsen Jun 24 '13 at 18:20
  • Note that the only reason to use the second form would be to avoid cluttering the namespace. It's not faster (it's faster than using an IIFE to avoid the x variable but you rarely need to increment two variables without being in a local scope that you can pollute). – Denys Séguret Jun 24 '13 at 18:30