Fizz Buzz
Write a TypeScript function that returns an array of strings from 1 to n. For multiples of 3, store 'Fizz' instead of the number. For multiples of 5, store 'Buzz'. For multiples of both 3 and 5, store 'FizzBuzz'.
Initialize an empty array. Loop from 1 to n. Use conditionals with the modulo operator to check divisibility. Push the appropriate string to the array based on the conditions.
The order of conditions matters: check for FizzBuzz (multiple of 15) first since numbers like 15 are multiples of both 3 and 5. If you check Fizz first, you would incorrectly output 'Fizz' for 15 instead of 'FizzBuzz'.
Edge cases include n = 0 (return empty array), n = 1 (return ['1']), and n = 15 (contains FizzBuzz at position 15). The function uses a for loop with string array building and the push() method.
FizzBuzz is a classic programming interview question that tests basic control flow and modulo arithmetic. TypeScript's type annotations document the function signature clearly, making the code self-documenting with the return type string[].
The modulo operator % returns the remainder of division. If i % 15 === 0, i is divisible by both 3 and 5, so it's a FizzBuzz number. The strict equality operator === ensures type-safe comparison without coercion.
Example Input & Output
Algorithm Flow

Solution Approach
Write a TypeScript function that returns an array of strings from 1 to n. For multiples of 3, store 'Fizz' instead of the number. For multiples of 5, store 'Buzz'. For multiples of both 3 and 5, store 'FizzBuzz'.
Initialize an empty array. Loop from 1 to n. Use conditionals with the modulo operator to check divisibility. Push the appropriate string to the array based on the conditions.
The order of conditions matters: check for FizzBuzz (multiple of 15) first since numbers like 15 are multiples of both 3 and 5. If you check Fizz first, you would incorrectly output 'Fizz' for 15 instead of 'FizzBuzz'.
Edge cases include n = 0 (return empty array), n = 1 (return ['1']), and n = 15 (contains FizzBuzz at position 15). The function uses a for loop with string array building and the push() method.
FizzBuzz is a classic programming interview question that tests basic control flow and modulo arithmetic. TypeScript's type annotations document the function signature clearly, making the code self-documenting with the return type string[].
The modulo operator % returns the remainder of division. If i % 15 === 0, i is divisible by both 3 and 5, so it's a FizzBuzz number. The strict equality operator === ensures type-safe comparison without coercion.
Best Answers
function fizzBuzz(n: number): string[] {
var result: string[] = [];
for (var i = 1; i <= n; i++) {
if (i % 15 === 0) result.push('FizzBuzz');
else if (i % 3 === 0) result.push('Fizz');
else if (i % 5 === 0) result.push('Buzz');
else result.push(String(i));
}
return result;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
