I have a variable and if that variable is a object I would like to call a method on that object, if not I want to do nothing. I’m wondering if there is any reason why I shouldn’t do it like this. Answer The quick answer is yes, foo && foo.bar() won’t throw an exception if foo is null, and
Tag: shorthand
Ternary shorthand for foo ? foo : bar
I realized I am using the ternary operator most of the time as following: foo ? foo : bar; This becomes cumbersome, as the variable length gets quite long, e. g. appModel.settings.notifications ? appModel.settings.notifications : {}; Is there any shorthand or more elegant way of doing this? Perhaps ES6 or ES7? Answer You can write it like this : you
Shorthand if/else statement Javascript
I’m wondering if there’s a shorter way to write this: I initially tried x = y || 1, but that didn’t work. What’s the correct way to go about this? Answer Note that var x = y || 1; would assign 1 for any case where y is falsy (e.g. false, 0, “”), which may be why it “didn’t work”