Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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" }, } 
like image 511
Jorge Olivero Avatar asked Feb 04 '14 20:02

Jorge Olivero


People also ask

Can we use if condition inside object in JavaScript?

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

How do you add a condition to an object?

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.

When should we use if statement in JavaScript?

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.

What is correct way to write an if statement in JavaScript?

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 () {} .


2 Answers

No, however you can use the ternary operator:

var testBoolean = true;  var object = {   attributeOne: "attributeOne",   attributeTwo: testBoolean ? "attributeTwo" : "attributeTwoToo" } 
like image 194
Matt Avatar answered Sep 26 '22 09:09

Matt


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

var x = {   y: (function(){        if (true) return 'somevalue';      }()) }; 
like image 21
Tony Nardi Avatar answered Sep 22 '22 09:09

Tony Nardi