In javascript interviews, the most frequently asked question is "FizzBuzz." The goal of asking this question is to see how you approach solving the problem rather than the solution itself.
The following is an example of a question. Print the numbers 1 to 100 that meet the following conditions:
- Print "Fizz" if a number is divisible by 3.
- Print "Buzz" if a number is divisible by 5.
- Print "FizzBuzz" if the number is divisible by both 3 and 5.
- else print the number itself.
The solution is straightforward, but the approach is critical.
A newcomer would do it like this:
function fizzBuzz(){
for(let i = 1; i <= 100; i++){
if(i % 3 === 0 && i % 5 === 0){
console.log('FizzBuzz');
}else if(i % 3 === 0){
console.log('Fizz');
}else if(i % 5 === 0){
console.log('Buzz');
}else{
console.log(i);
}
}
}
This is how people with some experience would do it:
function fizzBuzz(){
for(let i = 1; i <= 100; i++){
// instead of checking if divisible by both 3 and 5 check with 15.
if(i % 15 === 0){
console.log('FizzBuzz');
}else if(i % 3 === 0){
console.log('Fizz');
}else if(i % 5 === 0){
console.log('Buzz');
}else{
console.log(i);
}
}
}
fizzBuzz()
However, a pro developer🚀 would do it as follows:
function fizzBuzz() {
for(let i = 1; i <= 100; i++){
console.log(((i%3 === 0 ? "fizz": '') + (i% 5 === 0 ? "buzz" : ''))|| i)
}
}
fizzBuzz()
I hope this helps you guys solve it like a pro. Any additional pro solutions are welcome.
Please ❤️ it and share it your with friends or colleagues. Spread the knowledge.
Thats all for now. Keep learning and have faith in Javascript❤️
Top comments (3)
hmmm:
🔥
That's amazing