Coming from the rubyesque crowd I was very fond of the following 'lazy' initialization pattern.
myhash[:property]||='value'
And sometimes during my career I adapted it to javascript as following:
myhash.property || (myhash.property = 'value')
A co-worker remarked that it's quite irregular, and to be honest I can't remember seeing other people using that pattern.
So my question is; Is it just another innocent initialization flavor or am I unintentionally asking for trouble?
Given the execution flow of conditional statements like that I suppose It is possible to use it as an if statement aswell:
aModel.valid && aModel.save();
or even something more insane..
willYouMarryMe === 'yes' && (function(){
console.log('Wohoo!');
})();
Lazy initialization is often used in JavaScript, but it's more common to see:
namespace.property = namespace.property || 'default';
As far as calling functions is concerned, it's good practice to use if statements where they apply instead of && and ||. Minifiers will often automatically convert the if statements into && and || for production to reduce file size, so it's not necessary to do so directly.
Writing easily readable code makes future maintenance easier:
Good:if (!foo) {
bar();
}
Writing code that's harder to read makes code harder to maintain. Particularly because using one clever trick often indicates that other clever tricks are going to be used:
Bad:foo || bar();
The one major exception to this with regard to functions tends to be when calling console.log:
window.console&&console.log('lorem', 'ipsum');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With