In some javascript code I'm working on refactoring I've handled cases where I wanted to default an object property to true without having to go through the code-base and add the property to every instance of the object by doing something like this:
if(typeof(thisBool) === 'undefined' || thisBool) {
//do cool stuff here;
}
so for existing instances I only had to fix up the model in cases where I wanted to set thisBool
to some value calculated somewhere else, or to set it to false; if it was unset then this code treated it as true.
The objects are built dynamically when used - they're not defined classes, but are "instantiated" something like this:
var thing1 = {
Name: 'thing No 1',
HasCat: false,
[thisBool: true]
};
and thing1
is passed into the function
Is this a terrible idea? I'm updating that code (and all of the instances) so now is the time to fix this, if it's a code smell.
For my own part I would rather be more explicit, but I also see the value in not having to supply a thisBool: true
in hundreds of places, where by default thisBool
should be true. Is there a better way to achieve this?