# JavaScript crashes while squaring number

• Java
Is this a legit code for printing out squares of numbers betwean 100 and 150 ??? Seems to crash everytime.

for (var i=100; i<151; i*i)
{
var square = i;
console.log(square);
}

Need help :)

## Answers and Replies

phinds
Gold Member
Is this a legit code for printing out squares of numbers betwean 100 and 150 ??? Seems to crash everytime.

for (var i=100; i<151; i*i)
{
var square = i;
console.log(square);
}

Need help :)

No, the upper limit on your loop is a function of the loop variable, which doesn't make sense, and you have no code IN the loop that is actually squaring anything.

uart
The problem is not really the upper limit (i<151) but the lack of an increment for the loop variable.

Your "increment" seems to be "i*i", but that's not assigned to anything, so it makes no changes to "i".

If you had written "i=i*i" then it still wouldn't work, but at least it wouldn't crash (presumably due to the infinite loop).

You need to increment "i" within the loop, and assign "i*i" to your variable "square" within the loop body.

Last edited:
You need to increment "i" within the loop, and assign "i*i" to your variable "square" within the loop body.

The general syntax of the for loop might be expressed like:

for ( start; stop; increment) {
//do stuff
}

By "You need to increment "i" within the loop" you mean i should increment within the body of the statement?

Like:

for (var i=100; i<151; i=square)
{
var square = i*i;
console.log(square);
}

I guess not. Since I get the error: "TypeError: Property 'eval' of object [object Window] is not a function".

I didn't know what to put into the "increment" part of the for loop - so I assigned square (or tried to assign, if it is not allowed).

I would very much appreciate clarifications :)

Last edited:
uart
The general syntax of the for loop might be expressed like:

for ( start; stop; increment) {
//do stuff
}

By "You need to increment "i" within the loop" you mean i should increment within the body of the statement?

Like:

for (var i=100; i<151; i=square)
{
var square = i*i;
console.log(square);
}

Ok it's just your "increment" that's wrong now. The increment is extremely important. The loop variable "i" must be increased each time the loop is executed otherwise it will never reach 151 and therefore the loop with never end. (this is why your program is "hanging").

Try
Code:
for (var i=100; i<151; i=i+1)
{
var square = i*i;
console.log(square);
}

BTW. Most people prefer to use the increment operator "i++", which does the same as thing "i=i+1". I used the "i=i+1" for clarity, but either "i++" or "i+=1" will work the same way.

Last edited: