at. at. - 1 year ago 109
Javascript Question

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

I love Ruby's

mechanism. If a variable doesn't exist or is
, 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 Source

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 :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download