Ruby || = (or equal) in JavaScript?

I like the Ruby ||= mechanism. If the variable does not exist or is nil , create it and set it somehow:

 amount # is nil amount ||= 0 # is 0 amount ||= 5 # is 0 

I need to do something similar in JavaScript now. What is the convention or the right way to do this? I know that ||= syntax is invalid. 2 obvious ways to handle this:

 window.myLib = window.myLib || {}; // or if (!window.myLib) window.myLib = {}; 
+107
javascript syntax ruby
30 sept '13 at 7:20
source share
4 answers

Both are absolutely correct, but if you are looking for something that works like ||= in ruby. The first method is variable = variable || {} variable = variable || {} is the one you are looking for :)

+121
Sep 30 '13 at 7:27
source share

You can use the logical operator OR || which evaluates its right operand if lVal is a false value.

False values ​​include, for example, null, false, 0, "", undefined, NaN

 x = x || 1 
+18
Sep 30 '13 at 7:28
source share

If you work with objects, you can use destructuring (starting with ES6) as follows:

 ({ myLib: window.myLib = {} } = window); 

... but you get nothing from the accepted answer, except for confusion.

+4
Jun 06 '17 at 2:26 on
source share

Ruby || = assignment of operator short circuits. You might think about this:

 return a || a = b 

So in javascript this looks very similar:

 return a || (a = b); 

As you can see from the comments below, this literal ruby ​​form is less effective than the standard javascript idiom a = a || b.

For reference: http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html

-2
Nov 25 '15 at 4:37
source share



All Articles