Sunday, December 29, 2024
Google search engine
HomeLanguagesJavascriptFizzbuzz Program in JavaScript

Fizzbuzz Program in JavaScript

In this article, we are going to learn how can we create ‘fizzbuzz’ in JavaScript. In this, we will have a number and we have to print counting till that number, but multiples of 3 are replaced with “Fizz,” multiples of 5 with “Buzz,” and multiples of both with “FizzBuzz”.

Example:

Input: n = 3
Output: [1 2 Fizz]
Input: n = 5
Output: [1 2 Fizz 4 Buzz]

Using for… loop

In this approach, a FizzBuzz program can be created using a for loop that iterates from 1 to a specified number. Conditionally, replace multiples of 3 with “Fizz,” multiples of 5 with “Buzz,” and both with “FizzBuzz,” then print the result.

Example: This example shows the creation of fizbuzz program in JavaScript.

Javascript




let fizzBuzz = function (n) {
  
    const arr = []
    for (i = 1; i <= n; i++) {
        if (i % 15 === 0) arr.push("FizzBuzz")
        else if (i % 3 === 0) arr.push("Fizz")
        else if (i % 5 === 0) arr.push("Buzz")
        else arr.push(i.toString())
    }
    return arr
  
};
console.log(fizzBuzz(15))


Output

[
  '1',        '2',
  'Fizz',     '4',
  'Buzz',     'Fizz',
  '7',        '8',
  'Fizz',     'Buzz',
  '11',       'Fizz',
  '13',       '14',
  'FizzBuzz'
]

Time Complexity: O(n), where n is the input number.

Space Complexity: O(n), because of array creation.

Using recursion

In this approach, this recursive JavaScript function, myFunction, generates FizzBuzz values or numbers up to a given limit by checking divisibility conditions and accumulating results in an array.

Example: This example shows the creation of fizbuzz program in JavaScript.

Javascript




function myFunction(number, current = 1, results = []) {
    if (current > number) {
        return results;
    }
  
    let output = [];
    if (current % 3 === 0) output.push('Fizz');
    if (current % 5 === 0) output.push('Buzz');
  
    if (output.length === 0) {
        results.push(current);
    } else {
        results.push(output.join(''));
    }
  
    return myFunction(number, current + 1, results);
}
  
const fizzBuzzArray = myFunction(15);
console.log(fizzBuzzArray);


Output

[
  1,          2,
  'Fizz',     4,
  'Buzz',     'Fizz',
  7,          8,
  'Fizz',     'Buzz',
  11,         'Fizz',
  13,         14,
  'FizzBuzz'
]

Time Complexity: O(n), where n is the input number.

Space Complexity: O(n), because of a call stack in recursion.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments