Reputation: 21
I'm trying to figure out if there is a way to console.log a set of numbers that are incremented by multiplication or how one can increase or decrease the increment of a for loop with something other than i++, ++i, i+=3
yes, I've looked everywhere for this, but maybe I'm thinking about a wrong loop or method. Every time I try to run this code it won't stop and it crashes my browser so I can't play around with it anymore to try to figure out what's wrong.
for (let ok = 2; ok < 100; ok * 3) {console.log(ok)}
My question is, why does the limit of 100 not work and how to multiply and console.log
those numbers?
Upvotes: 1
Views: 2319
Reputation: 557
Something like this should work, yeah
for (let ok = 2; ok < 100; ok = ok * 3) {console.log(ok)}
Edit: To precise why this works, the final-expression is a piece of code that is fired at the end of every loop, so you could even make it a function call if you wanted. But be careful of infinite loops
Upvotes: 0
Reputation: 1
The code is currently just multiplying ok
by 3 but not setting ok
to be the new value. This means the code runs forever as ok
is not being increased.
Instead try something like:
for (let ok = 2; ok < 100; ok = ok * 3) {console.log(ok)}
or the equivalent:
for (let ok = 2; ok < 100; ok =* 3) {console.log(ok)}
Upvotes: 0
Reputation: 1
Here you go:
for (let ok = 2; ok < 100; ok *= 3) {console.log(ok)}
This is the other way to write it:
for (let ok = 2; ok < 100; ok = ok * 3) {console.log(ok)}
Upvotes: 0
Reputation: 158
Use ok*=3
since variable ok won't be updated with your statement
Upvotes: 1
Reputation: 1323
Try this:
for (let ok = 2; ok < 100; ok *= 3) {console.log(ok)}
Why does this work? Because x *= y
is short for the reassignment statement: x = x * y
. Your code is not increasing the value of ok
; on every single iteration, you're just going to get 2 * 3
, because ok
is still 2. That's why your loop never ends - it never approaches 100.
Upvotes: 2