Reputation: 29
This is a solution for FizzBuzz (it prints the numbers 1 to 100, but prints "Fizz" for numbers that are divisible by 3, "Buzz" for numbers divisible by 5, and "FizzBuzz" for numbers divisible by both).
for (var n = 1; n <= 100; n++) {
var output = "";
if (n % 3 == 0)
output += "Fizz";
if (n % 5 == 0)
output += "Buzz";
console.log(output || n);
}
I don't understand how the ||
works in console.log(output || n);
Usually a boolean expression like that evaluates to either true or false.
Upvotes: 1
Views: 1987
Reputation: 75
The OR operator retuns the left side if it's truthy, if it's falsy retuns the right side. Same:
var foo = output || n;
console.log(foo);
Upvotes: 2
Reputation: 1201
""
, the empty string, is considered a "falsy" value in JavaScript. That is, when used in an expression involving boolean operators, ""
is treated as false
. The MDN has a resource on falsy values in JavaScript.
For example, the code snippet if ("") console.log("Hello, World!");
will not produce any output, as the if
statement evaluates its expression to be false
.
In the case of your solution to FizzBuzz, should output
never have anything appended to it, the expression output || n
will effectively be false || n
, and due to the way JavaScript evaluates boolean operators, the expression will evaluate to n
.
Upvotes: 1
Reputation: 705
When there is no output from the if
's, it's print the number (n). This is what ||
do here ;)
Upvotes: 0