Reputation: 5144
Is there a way to use a logical operator for object properties? For example, can I do something like:
var myObj = {};
var prop = myObj.prop || 0;
Where prop
gets set to 0 if prop
isn't a property of myObj? But here,
var myObj = {};
myObj.prop = 2;
var prop = myObj.prop || 0;
myObj.prop
is set to 2 because prop
exists in this case.
Upvotes: 1
Views: 600
Reputation: 587
A simpler varient would be to set the property in your fallback
var prop = myObject.prop || (myObject.prop = 0);
Upvotes: 0
Reputation: 159875
No, but you can use the ternary conditional operator for it:
var has = Object.prototype.hasOwnProperty;
var prop = has.call(myObj, 'prop') ? 0 : undefined;
It is not perfect (future references to prop
will no longer be a ReferenceError
in the event that myObj
does not have a prop
property), but there is no better way without using let
:
if (!has(...)) {
let prop = 0;
// Do things with `prop` here
}
// prop is still a ReferenceError outside of the if block
Upvotes: 2
Reputation: 6349
You could do something like this. You can use hasOwnProperty
method to check that object has property or not
var myObj = {};
var prop = myObj.hasOwnProperty('prop') || 0;
Upvotes: 0