for(var i=1;i<100;i++){
console.log(((['Fizz'][i%3] || '') + (['Buzz'][i%5] || '')) || i)
}
What does ['Fizz'][i%3]
stand for? Which ES version is this a part of?
for(var i=1;i<100;i++){
console.log(((['Fizz'][i%3] || '') + (['Buzz'][i%5] || '')) || i)
}
What does ['Fizz'][i%3]
stand for? Which ES version is this a part of?
It’s original JS using syntax that was there before ECMA got involved.
['Fizz']
is an array literal.
['Fizz'][0]
is 'Fizz'
['Fizz'][1]
is undefined
(etc)
i%3
will give you the remainder when you divide i
by 3
The output for this is:
1 %3 = 1 -> undefined
2 %3 = 2 -> undefined
3 %3 = 0 -> `Fizz`
1 %3 = 1 -> undefined
The ||
catches the 'undefined' and makes it ''
.
(['Fizz'][i%3] || '')
can be translated into
let fizz = ['Fizz'];
let remainder = i % 3;
if(fizz[remainder] != undefined) {
return fizz[remainder];
}
else {
return '';
}
It instantiates an array with ['Fizz']
which then returns a "pointer" to the array object in memory. Then immediately is accessed by an array access brackets [] to get an index.
If the index exists it returns the value that corresponds to that index. in this case there is only the index 0, which contains the string value 'Fizz'
.
By using the modulus operator it returns the remainder if you were to keep subtracting the given value until you reach 0. Read more here: Understanding The Modulus Operator %
So every time i
has the value that is a multiple of 3, the remainder will be 0, resulting in a hit on an existing index. When the remainder isn't 0, it returns undefined
undefined
is a falsy value which can then be bypassed with a default return value with the ||
OR operator. A "filled" string like 'Fizz'
is a truthy value, so that would return itself. The OR operator then returns an empty string.
The above snippet translated in longer code would become:
for(var i=1;i<100;i++){
let fizz = ['Fizz'];
let buzz = ['Buzz'];
let remainder_fizz = i % 3;
let remainder_buzz = i % 5;
let endstring = '';
if(fizz[remainder_fizz] != undefined) {
endstring += fizz[remainder_fizz];
}
else {
endstring += '';
}
if(buzz[remainder_buzz] != undefined) {
endstring += buzz[remainder_buzz];
}
else {
endstring += '';
}
if(endstring.length == 0) {
endstring = i;
}
console.log('long logic:',endstring, ' | short logic:',((['Fizz'][i%3] || '') + (['Buzz'][i%5] || '')) || i);
}