JS Assignment 5: For Loops
JerehlDyer (2)

What am I doing wrong here?

function exerciseTwo(){
let count = 0;
// In this exercise write your own for loop (you can look at the syntax above).
// It should loop 10 times.
// You are given a variable called: count .
// For each loop reassign count to the current value of count + 1 .
for( let count = 0; count <= 10; count++)
//Please write your answer in the line above.
return count;
}

You are viewing a single comment. View All
Answered by heyitsmarcus (284) [earned 5 cycles]
View Answer
heyitsmarcus (284)

@JerehlDyer Typically, you wouldn't do as I did there. That was done to satisfy the algorithm. We had to put those curly braces in for the for loop because if we didn't, JavaScript determines that the line after any kind of loop such as for or a conditional such as if belongs with the for or if or whatever loop/conditional it might be.

As an example, let's say you have this function:

function a() {
	let count = 0;
	for (count = 0; count < 10; count++) 
		count++;
		return count;
}

I formatted it a bit weirdly on purpose. And this is why I always use brackets. With the way this is formatted, you'd assume that the for loop executes just once, to add 1 to count, and then returns the count variable. What actually happens is that only the very next line counts as part of the for loop (the count++). The line return count executes after the for loop.

A better formatted example that is easier to read and understand:

function a() {
	let count = 0;
	for (count = 0; count < 10; count++) {
		count++;
	}
		
	return count;
}

Does that make sense?