FizzBuzz (JavaScript)

Photo by Crissy Jarvis on Unsplash

When I first started learning how to code, FizzBuzz was a mystery to me. But as I continue to practice coding, the problem has become as simple as 1 + 1 to me. I thought it would only be right to return to the new devs who come after me to walk through how I solved FizzBuzz.

You are given an integer (n). Print 1 to n, but if the current number is divisible by 3, print “Fizz.” If the current number is divisible by 5, print “Buzz.” If it is divisible by both 3 and 5, print “FizzBuzz.” Else, print the current number.

function FizzBuzz(n) {
for (let i = 0; i < n.length; 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(n)
}
}
}

Basically, we would use a for loop to iterate through a collection of integers, starting with 1 and incrementing until we reach n. If i is divisible by 3 and 5, “FizzBuzz” is logged onto the console. Otherwise, if it is divisible by 3 or 5, “Fizz” or “Buzz” will be logged, respectively. If none of these conditions are met, the integer is logged.

The order of commands is important; we would first have to check if i is divisible by both 3 and 5. This is because if we first check only if i is divisible by 3, if i happens to meet the condition, the command will be executed, printing “Fizz” instead of the correct “FizzBuzz,” and the for loop will continue onto the next integer without checking any other conditions.

--

--

--

Laotian-American woman pursuing my passion for mentally stimulating and complex problem-solving through programming.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Chindalath Traymany

Chindalath Traymany

Laotian-American woman pursuing my passion for mentally stimulating and complex problem-solving through programming.

More from Medium

EcmaScript vs JavaScript

Closure in Javascript

What is hoisting in JavaScript?

Devslopes: Main Function of Javascript