Search code examples
javascriptrecursionfizzbuzz

I am trying to better understand recursion by using the FizzBuzz problem in javascript


I don't understand line 18? If the input is 100 how does program print out the number 1 first and end with the number 100 in the array? Any help would be appreciated.

function fizzBuzz(n){
  //create empty array called results
  //create base case for when n === 1
  //recurse and push value to array
  var results = [];
  if(n === 1){
    return [1];
  } else {
    if(n % 3 === 0 && n % 5 === 0){
      results.push('FizzBuzz')
    } else if (n % 3 === 0){
      results.push('Fizz')
    } else if (n % 5 === 0){
      results.push('Buzz')
    } else {
      results.push(n);
    }
      return fizzBuzz(n - 1).concat(results); // ???
    }
}

console.log(fizzBuzz(100));


Solution

  • The first thing to realize is that every call to fizzBuzz returns an array - it does not add to an existing array, it creates a new one every time.

    So, if the input n is 1, it simply returns a single-element array with 1 in it.

    If n > 1, there will be a recursive call. "results" has already been created as an empty array, so the .push() statements add a single element to that array:

    If n is divisible by 3 and 5, the array will be ['FizzBuzz'] If n is divisible by 3 only, the array will be ['Fizz'] If n is divisible by 5 only, the array will be ['Buzz'] Otherwiese, the array will be [n] whatever n is.

    Since n > 1 (or we wouldn't be here) we have to call FizzBuzz again with the next-lower n and concatenate its result to ours. This is how the long array is built - by concatenating the array returned from recursive calls to FizzBuzz.