function add(num) {
var sum;
for (var i = 1; i < num + 1; i++){
sum = (sum || 0) + i;
};
return sum;
}
add(9);
What is a keyword to describe the behavior for defining sum when it gets added to "i" in the for loop? Is this a ternary operation? Obviously the first time it loops through it is undefined, so javascript chooses 0. Why is that?
The "or" operator ||
works like this:
Since undefined
is not truthy, sum || 0
is zero the first time through the loop.
I don't know that there's a specific term for this behavior. * It's simply a convenient way to initialize a variable which may not have been pre-initialized. In your example, it would make more sense to initialize the variable at the start:
function add(num) {
var sum = 0;
for (var i = 1; i < num + 1; i++){
sum += i;
};
return sum;
}
condition ? expr1 : expr2
But note his caveat:
It's a common logic bug to use this pattern where the first operand could legitimately be falsy. Never use
var a = b || c
where, say,0
is a valid value forb
.