Reputation: 3705
I cannot expain more than an example:
let a = 0;
let b = 2;
let condition;
condition ? a = 2; b = 10 : false
console.log(a, b)
Why this syntax is wrong?
Upvotes: 3
Views: 7608
Reputation: 59
I am relatively new to javascript and I am not really sure about my answer here, but aren't ternary operators somewhat used like this:
condition ? a = 2 : b = 10;
Or in your case:
condition ? (a = 2, b = 10) : false;
Upvotes: 0
Reputation: 386624
You need to wrap the assignments in parenthesis and use the comma operator which separates the assignments, instead of semicolon, which separates statements.
The semicolon ends the conditional (ternary) operator ?:
before reaching the :
, which is a needed part of the syntax and this leads to an error.
let a = 0;
let b = 2;
let condition = true;
condition ? (a = 2, b = 10) : false;
console.log(a, b);
Instead of taking a conditional operator, you could use logical AND &&
.
let a = 0;
let b = 2;
let condition = true;
condition && (a = 2, b = 10);
console.log(a, b);
Finally the best approach by using if
.
let a = 0;
let b = 2;
let condition = true;
if (condition) {
a = 2;
b = 10;
}
console.log(a, b);
Upvotes: 5
Reputation: 5522
let condition1 = false;
let {a=0,b=2} = condition1 ? {a:2,b:10} : {}
console.log(a, b)
let condition2 = true;
let {c=0,d=2} = condition2 ? {c:2,d:10} : {}
console.log(c, d)
Upvotes: 0
Reputation: 3011
Just to give another option not yet posted, if you don't want to use a standard if..else
, you could also use ES6's neat destructuring assignment, which is particularly handy if you've already got an array of values that you want to assign from.
For example: (I've used two different conditions to show both outcomes)
let a = 1 > 2 ? [y, z] = [2, 10] : false;
console.log(a); //a = false;
2 > 1 ? [y, z] = [2, 10] : false;
console.log(y, z); //y = 2, z = 10;
Upvotes: 2
Reputation: 711
You cant run more than 1 "line" or "command" (ending with a semicolon) in the ternary operation. You could do
let condition;
let a = condition ? 2: 0;
let b = condition ? 10 : 2;
console.log(a, b);
which will work for your purpose or if you want to change a
and b
in a later point
let a = 0;
let b = 0;
let condition;
//later
a = condition ? 2 : a;
b = condition ? 10 : b;
both these examples will work with what you need
Upvotes: 0
Reputation: 138277
Its because of operator predescendence, and the ternary only works with expressions, so might just do:
condition ? ((a = 2), (b = 10)) : false
However, i would prefer:
if(condition) {
a = 2;
b = 10;
}
Upvotes: 3