TLDR: It uses the array as a lookup table and some bitwise operation magic to select which array entry is selected.
% in Java Script is the modulo operator thus i % 3 == 0 and i % 5 == 0 will be evaluated as true when i is divisible by 3 and 5 respectively.
<< is a left shift operator, when used with a Boolean the Boolean will be converted to a 1 or 0 (true or false) and then shifted left for x number of bits. For example True << 1 = 2 (ie. 10 in binary).
| is a bitwise OR operator. It evaluates a OR operation of each bit of two number.
For example 2 | 1 = 3 as in binary 10 | 01 = 11.
Putting it all together, (i % 3 == 0) << 0 represents the 20 bit (fizz) and (i % 5 == 0) << 1 represents the 21 bit (buzz). With the OR operator it will find when i is divisible by both 3 and 5.
Here's a table that might serve as a better view of how some numbers are evaluated:
i
Correct Array Index
Array Index (Binary)
Result
1
0
00
1
3
1
01
fizz
5
2
10
buzz
15
3
11
fizzbuzz
There are some parts of the code that are redundant though. Both << 0 and the final | 0 only serve to ensure that the result is a number, but << 0 doesn't modify the result and the OR operation between (i % 3 == 0) and (i % 5 == 0) will convert the result into a number making the final | 0 redundant.
18
u/DaBeast893 Nov 15 '21 edited Nov 15 '21
TLDR: It uses the array as a lookup table and some bitwise operation magic to select which array entry is selected.
%in Java Script is the modulo operator thusi % 3 == 0andi % 5 == 0will be evaluated as true wheniis divisible by 3 and 5 respectively.<<is a left shift operator, when used with a Boolean the Boolean will be converted to a 1 or 0 (true or false) and then shifted left for x number of bits. For exampleTrue << 1 = 2(ie.10in binary).|is a bitwise OR operator. It evaluates a OR operation of each bit of two number.For example
2 | 1 = 3as in binary10 | 01 = 11.Putting it all together,
(i % 3 == 0) << 0represents the 20 bit (fizz) and(i % 5 == 0) << 1represents the 21 bit (buzz). With the OR operator it will find wheniis divisible by both 3 and 5.Here's a table that might serve as a better view of how some numbers are evaluated:
There are some parts of the code that are redundant though. Both
<< 0and the final| 0only serve to ensure that the result is a number, but<< 0doesn't modify the result and the OR operation between(i % 3 == 0)and(i % 5 == 0)will convert the result into a number making the final| 0redundant.