Setting attributeTwo using an if statement. What is the correct way to do this?
var testBoolean = true;
var object = {
attributeOne: \"attributeOne\",
a
Indeed you can but why don't you do the conditional statement before assigning it to object attribute. The code would be nicer.
No, however you can use the ternary operator:
var testBoolean = true;
var object = {
attributeOne: "attributeOne",
attributeTwo: testBoolean ? "attributeTwo" : "attributeTwoToo"
}
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"
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"
}
You can use an if statement, if it is within a immediately invoked function.
var x = {
y: (function(){
if (true) return 'somevalue';
}())
};