Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
117
rated 0 times [  123] [ 6]  / answers: 1 / hits: 53358  / 11 Years ago, mon, september 30, 2013, 12:00:00

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 = {};

More From » ruby

 Answers
0

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


[#75346] Friday, September 27, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
longd

Total Points: 616
Total Questions: 110
Total Answers: 101

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
;