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
  • 249,902
  • 55
  • 405
  • 483

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
  • 959,406
  • 173
  • 1,780
  • 1,769
1

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

anyaelise
  • 82
  • 1
  • 6
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
  • 113,669
  • 10
  • 50
  • 103
  • 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