at. at. - 2 months ago 10
Javascript Question

Ruby's ||= (or equals) in JavaScript?

I love Ruby's

||=
mechanism. If a variable doesn't exist or is
nil
, then create it and set it equal to something:

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


I need to do something similar in JavaScript now. What's the convention or proper way to do this? I know
||=
is not valid syntax. 2 obvious ways to handle it are:

window.myLib = window.myLib || {};

// or

if (!window.myLib)
window.myLib = {};

Answer

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

Comments