Say you have
var foo = {};
The line that is confusing you would be
foo.bar = foo.bar ? foo.bar + 1 : 1; // line A
Ask yourself
- What is
foo.barat the start? It is undefined, we didn't givefooa property bar - What is
foo.barafter the first time line A is executed? It is1;foo.barwas undefined which is falsy so the ternary operator gave us back1 - What is
foo.barafter the second time line A is executed? It is2;foo.barwas1which is truthy, so the ternary operator gave us backfoo.bar + 1
Line A can be repeated until you run out of numbers or the world explodes
Writing it like this is a way to solve the undefined + 1 problem, which would give NaN
An equally valid solution (which I find a bit cleaner to read personally) would be to do
foo.bar = (foo.bar || 0) + 1;
Answer from Paul S. on Stack OverflowYou can spread an array inside of an array, in order to keep items array clean, when the condition is false.
Here's how you can do it:
// Will result in ['foo', 'bar']
const items = [
'foo',
... true ? ['bar'] : [],
... false ? ['falsy'] : [],
]
console.log(items)
Explanations:
As you can see the ternary operator always returns an array.
If the condition is true, then it returns ['bar'], otherwise an empty array [].
After that we spread out ... the resulted array (from the ternary operation) and the array's items are pushed to the parent array.
If there aren't any array items (when the ternary check is false), then nothing will be pushed, which is our goal.
In other answer I explained the same idea, but for objects. You can check it too here.
I'd do this
[
true && 'one',
false && 'two',
1 === 1 && 'three',
1 + 1 === 9 && 'four'
].filter(Boolean) // ['one', 'three']
Note that this will also remove falsy values, such as empty strings.
Whenever the return statement is executed the function doesn't proceed further and returns a value.
In the first case the code will return false only if the condition is true if condition is false then it will proceed further. In the first case the function will return false after the end of the loop.
In the second example there is no condition to execute return so it will return in first iteration and function will not execute further.
A function can only return once, so we can't put them in a loop. But if you really want to use a ternary operation you can do it like this
function check(arr, el) {
let check = false;
for (var i = 0; i < arr.length; i++) {
check = arr[i] === el ? true : check;
}
return check
}
but keep in mind that it will loop over all the elements in array even after it finds an equal element so an even better solution would be your first solution, which is
function check(arr, el) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === el) {
return true;
}
}
return false;
}