3

JavaScript has assignment operators corresponding to arithmetic ones: +=, -=, *=, /=, %=.

JavaScript also has assignment operators corresponding to bitwise ones: <<=, >>=, >>>=, &=, ^=, |=.

But it doesn't have assignment operators corresponding to logical ones: ||=, &&=.

Then, I can't do things like

aVeryLongVariableIdontWantToRepeat ||= 1;

In this other question it's explained why JS Java doesn't have such operators. I guess it's the same for JS.

But I want to know if there is a simple way to emulate them, avoiding

aVeryLongVariableIdontWantToRepeat = aVeryLongVariableIdontWantToRepeat || 1;
Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513

3 Answers3

2

No, there isn't. I feel like there should be more to this answer, but really, that's it. The shortest version of a = a || x is ... a = a || x.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

It might help you to investigate writing your code using Coffeescript, which has the ||= operator available.

anyaelise
  • 92
  • 1
  • 7
0

There isn't a shorter way: a = a || 1 is the simplest way to do it.

However, to avoid unnecessary assignment of values (slightly at the expense of readability) you can also do a || ( a = 1).

JSFIDDLE

var a,b='x';
a || ( a = 1 );
b || ( b = 2 );
console.log( a + ', ' + b ); // Outputs "1, x"
MT0
  • 143,790
  • 11
  • 59
  • 117
  • 1
    Of course, `a || (a = 1)` is no shorter than `a = a || 1` and we can count on the engine not to waste time on dead assignments. – T.J. Crowder Dec 23 '13 at 22:50