Can I write an if statement within a Javascript object when setting an attribute?

Setting attributeTwo using an if statement. What is the correct way to do this?

var testBoolean = true;

var object = {
  attributeOne: "attributeOne",
  attributeTwo: if (testBoolean) { "attributeTwo" } else { "attributeTwoToo" },
}

Answers:

Answer

No, however you can use the ternary operator:

var testBoolean = true;

var object = {
  attributeOne: "attributeOne",
  attributeTwo: testBoolean ? "attributeTwo" : "attributeTwoToo"
}
Answer

You can use an if statement, if it is within a immediately invoked function.

var x = {
  y: (function(){
       if (true) return 'somevalue';
     }())
};
Answer

you can also do by this method

var testBoolean = true;

var object = {
  attributeOne: "attributeOne"
}

1

if(testBoolean){
   object.attributeTwo = "attributeTwo"
}else{
   object.attributeTwo = "attributeTwoToo"
}

2

object.attributeTwo = testBoolean ? "attributeTwo" : "attributeTwoToo"
Answer

You can't use an if statement directly, but you can use ternary operator (aka conditional operator) which behaves the way you want. Here is how it would look:

var testBoolean = true;

var object = {
  attributeOne: "attributeOne",
  attributeTwo: testBoolean ? "attributeTwo" : "attributeTwoToo"
}
Answer

Indeed you can but why don't you do the conditional statement before assigning it to object attribute. The code would be nicer.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.