Sometimes, we want to write an if statement within a JavaScript object when setting an attribute.
In this article, we’ll look at how to write an if statement within a JavaScript object when setting an attribute.
How to write an if statement within a JavaScript object when setting an attribute?
To write an if statement within a JavaScript object when setting an attribute, we can use the ternary operator.
For instance, we write:
const testBoolean = true;
const object = {
attributeOne: "attributeOne",
attributeTwo: testBoolean ? "attributeTwo" : "attributeTwoToo"
}
console.log(object)
We set testBoolean
to true
.
And we set object.attributeTwi
to 'attributeTwo'
is testBoolean
is true
and 'attributeTwoToo'
otherwise.
As a result, we see that object
is {attributeOne: 'attributeOne', attributeTwo: 'attributeTwo'}
.
Conclusion
To write an if statement within a JavaScript object when setting an attribute, we can use the ternary operator.