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" }, }
You can use an if statement, if it is within a immediately invoked function.
To conditionally add a property to an object, we can make use of the && operator. In the example above, in the first property definition on obj , the first expression ( trueCondition ) is true/truthy, so the second expression is returned, and then spread into the object.
Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false. Use switch to select one of many blocks of code to be executed.
An if statement is written with the if keyword, followed by a condition in parentheses, with the code to be executed in between curly brackets. In short, it can be written as if () {} .
No, however you can use the ternary operator:
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'; }()) };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With