I've been staring at this for half an hour and can't find my error. I just have to make a simple for loop that can print something onto the console.
for(var i=0;i<4;i+1){
console.log(i);
}
It also is asking for a while loop and a do/while loop. I haven't done those yet, but I don't think that's the error. It says: SyntaxError: Unexpected token ILLEGAL
3 Answers 3
Your syntax is incorrect. You have to add the 1 to the i, which you are not currently doing.
for(var i=0; i<4; i+=1){
console.log(i);
}
The classic way, of course is to just do, but I think the first one is more elegant and passes JSLint (which is, of course, the only right way to write javascript).
for(var i=0; i<4; i++){
console.log(i);
}
If you want your loop to fully pass JSLint, you can do as follows:
var i; // at the top of your function
// ...
for (i = 0; i < 4; i += 1) {
console.log(i);
}
8 Comments
var inside the for pass JSLint?i += 1. When I write a loop, I put the var i outside the loop.i+1 is valid syntax, but it doesn't do what the OP intends to do (increment i), thus it's a logic error. I can also be very pedantic so feel free to ignore me ;)or how 'bout:
for(var i = 0; i < 4; )
console.log(i++);
Comments
I have run your code in Chrome console, and I think your code have no SyntaxError, but it will cause en endless loop.
If you want to run a four loop, you'd better change the code like this:
for(var i=0; i<4; i+=1){
console.log(i);
}
i + 1would not change the value ofiafter the stepsivariable is set to0and then never changed. The "Unexpected token ILLEGAL" error you quote doesn't make sense for the code shown - do you have more code that is not shown?