Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this lazy variable initialization pattern bad practice?

Tags:

javascript

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!');
})();
like image 833
telamon Avatar asked Feb 09 '26 23:02

telamon


1 Answers

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');
like image 132
zzzzBov Avatar answered Feb 12 '26 21:02

zzzzBov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!