Categories: Frontend TechQ & A

Code of the day – FizzBuzz in Javascript

FizzBuzz Test

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

c2.com

Here’s my solution:
Test Driven Development Approach

	
// TDD Readable
var getFizzBuzzStatements = function (len) {
	var arr = [],
	str = "";
	for (var i = 1; i <= len; i++) {
		str = (i % 3) ? "" : "Fizz";
		str += (i % 5) ? "" : "Buzz";
		arr.push(str||i);
	}
	return arr;
};
var fizzBuzz = function () {
	console.log(getFizzBuzzStatements(100).join("\n"));
};
fizzBuzz();

Alternative: One liner

// One liner
for (i = 1; i <= 100; i++)
	console.log((((i % 3) ? "" : "Fizz") + (i % 5 ? "" : "Buzz")||i) + "\n")

Alternative: Switches

var getFizzBuzzStatements = function (len) {
	var j,
	arr = [];
	for (var i = 1; i <= len; i++) {
		switch (i % 15) {
		case 0:
			arr.push("FizzBuzz");
			break;
		case 3:	case 6:	case 9:	case 12:
			arr.push("Fizz");
			break;
		case 5:	case 10:
			arr.push("Buzz");
			break;
		default:
			arr.push(i);
		}
	}
	return arr;
};
var fizzBuzz = function () {
	console.log(getFizzBuzzStatements(100).join("\n"));
};

Demo

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

View Comments

Share
Published by
Larry Battle

Recent Posts

What really is Data Science? Told by a Data Scientist

What REALLY is Data Science? Told by a Data Scientist - By Joma Tech

7 years ago

Video: How Water Towers Work

How Water Towers Work - Practical Engineering

7 years ago

Dev Tip: Simple tips to improve code reviews

Writing perfect code is a challenging process. That's where code reviews come in to help…

7 years ago

Video: How AI will change the 3d industry

"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"

7 years ago

Best Software Presentation for 2018

"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"

7 years ago

Dev Video: A Few Linux Shell Tips

My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…

7 years ago