1

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.

2
  • Do you only want prop set to 0 if myObj 1) doesn't have a property of its own named prop, 2) doesn't have a property anywhere in its prototype chain named prop or 3) has a property named prop (either in the sense of #1 or #2) but it is falsey? Commented Feb 14, 2014 at 22:03
  • I want what's behind option #1. Commented Feb 14, 2014 at 22:05

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

Comments

2
var prop = myObj.hasOwnProperty('prop') ? myObj.prop : 0

4 Comments

Just FYI, if myObj = Object.create(null) this will break - don't make unguarded references to things on Object.prototype.
@SeanVieira Lol, I think we are both taking something here for granted. When I run the current version of your code var has = Object.prototype.hasOwnProperty; var prop = has.call(myObj, 'prop') ? 0 : undefined; I get ReferenceError: myObj is not defined. The OP did include var myObj = {}; as the first line.
Matt, I left the var myObj = /* whatever you want on this side */ out of my answer to focus on the solution I was suggesting, but if you add the variable, everything will work, even if you use Object.create(null) as the value of myObj.
@SeanVieira As did I leave out var myObj = {}; since it's already in the OP's question.
0

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;

2 Comments

But that does set prop to the value of myObj.prop if it does exist.
If var myObj = Object.create(null) the next line will fail - best to use Object.prototype.hasOwnProperty instead.
0

A simpler varient would be to set the property in your fallback

var prop = myObject.prop || (myObject.prop = 0);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.