You have several options:
An
ifstatementif (ve.select) { price += ve.price; }Or if you prefer it on one line:
if (ve.select) price += ve.price;The conditional operator version you've shown:
price = ve.select ? price + ve.price : price;...but note that it does an unnecessary assignment when
ve.selectis falsy (though aspriceis presumably a simple variable that's not an issue; with an object property that might be an accessor property it can matter).Using the
&&(logical AND) operator:ve.select && price += ve.price;But note that this is really just an
ifstatement in disguise.Tamás Sallai's answer providing an alternative use of the conditional operator (
price += ve.select ? ve.price : 0;).
You have several options:
An
ifstatementif (ve.select) { price += ve.price; }Or if you prefer it on one line:
if (ve.select) price += ve.price;The conditional operator version you've shown:
price = ve.select ? price + ve.price : price;...but note that it does an unnecessary assignment when
ve.selectis falsy (though aspriceis presumably a simple variable that's not an issue; with an object property that might be an accessor property it can matter).Using the
&&(logical AND) operator:ve.select && price += ve.price;But note that this is really just an
ifstatement in disguise.Tamás Sallai's answer providing an alternative use of the conditional operator (
price += ve.select ? ve.price : 0;).
I'd reverse the ternary and use +=:
price += ve.select ? ve.price : 0;
Question on if/when to use Ternary Operators?
Javascript ternary operator syntax with object
So i am completly new to programming and learning thru codecademy.
I just got thru all the lessons about if else statements and when/how to use them but in their next lession they talk about Ternary Operator basically being a "shot handed" version of wirting an if else statement (if I am understanding that correctly) if I am understanding it correctly then my question is, is one more "professional" then the other or is it just based on what your coding or what lets say your boss is asking you to code
The other reason I ask is I want to devlope good habits now vs later down the road so using the example below is it I guess from a "real world" working senario is it better to use one over the other
For example; I know this is a very genaric and basic example but
let nightTime = true
if (nighTime) {
console.log('Nightime');
} else {
console.log('Daytime')
}vs
nightTime
? console.log('Nighttime')
: console.log('Daytime');Hello, i got some issues with the syntax for this line of code:
counter === null ? counter = {wins: 0, losses:0, ties:0};
It tells me there is some issue with the ';'. I never had such a problem with ternary operators before, it seems like to be related with the object inside of it. what would be the right declaration of it?
Thanks