Click here to Skip to main content
16,020,182 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi guys, I'm reading a JS book at the moment and one of the challenges had us loop over all integers between 1 - 100 and write "Fizz" if it's divisible by 3, "Buzz" if it's divisible by 5 and "FizzBuzz" if it's divisible by both, otherwise just log the number. I managed to work out the code for the problem but I'm unsure as to why the 'output' declaration gets reset every iteration rather than storing a long line of Fizzes and Buzzes. Here's the code:

for (let num = 1; num <= 100; num++){
	let output = "";
	if(num % 3 == 0) output += "Fizz";
	if(num % 5 == 0) output += "Buzz";
	console.log(output || num);
    }


What I have tried:

I've tried googling the question but I can't find anything specific as to why a variable sometimes resets each iteration, whereas sometimes it gets stored over and over to concatenate everything.
Posted
Updated 5-Jul-18 2:34am

1 solution

It's because you declare it inside the loop. Declare it outside the loop to concatenate each iteration:

let output = "";
for (let num = 1; num <= 100; num++){
	if(num % 3 == 0) output += "Fizz";
	if(num % 5 == 0) output += "Buzz";
	console.log(output || num);
}
 
Share this answer
 
Comments
Member 13899723 5-Jul-18 8:45am    
@Thaddeus Jones Ahhh that makes sense, every time it loops it sets the value to "" again, whereas if it were outside the loop it wouldn't get reset as it's not beeing reevaluated... Thanks for the clarity :)
CPallini 5-Jul-18 9:00am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900