jreu
jreu

Reputation: 17

JS having variable update in for-loop

I'm new to JavaScript and coding in general, and i'm running into a problem with for-loop. I tell the loop to repeat 5 times, and the loop is supposed to halve the given number(200) 5 times, resulting in 6.25. Currently it halves the 200 5 times, but I can't figure out how to save the number in variable after each loop correctly, so it just repeats 200/2 = 100, 200/2 = 100, 200/2 = 100, 200/2 = 100, 200/2 = 100.

How can I save result of each loop into variable and use the updated variable in the next run of the loop?

function toisto(t,a,o) {
//t = 5
//a = 200
//o is a function for halving
    for (var i = 0; i < t; i++) {
        var puolitustulo = o(a);
    }
    console.log(puolitustulo);
}

Upvotes: 0

Views: 1098

Answers (3)

Nabin Neupane
Nabin Neupane

Reputation: 26

Based on what you have there, This will be my solution. Instead of declaring the new variable on the loop you can simply pass the same variable (i.e. a) and get the halves. And to get the value of halves on each iteration simply, put the console output inside the for a loop.


function o(value)
{
    return value/2;
}


function toisto(t,a) {

    for (var i = 0; i < t; i++) {
        a = o(a);
      console.log(a);
    }
    
}

toisto(5,200);

Upvotes: 1

MishkaZi
MishkaZi

Reputation: 13

function o(a){
    return a/2;    
}

function toisto(t,a,o) {
//You define and initialize variable before loop
let puolitustulo =0;
    for (let i = 0; i < t; i++) {
        puolitustulo= o(a);
        //You need to update your a to new value
        a=puolitustulo;
    }
    console.log(puolitustulo);
}


toisto(5,200,o);

Upvotes: 1

Centmsn
Centmsn

Reputation: 51

To solve this problem You need to "update" variable a inside the loop.

function toisto(t, a, o) {
//t = 5
//a = 200
//o is a function for halving
    for (let i = 0; i < t; i++) {
        //assign new value to the variable in each iteration
        a = o(a);
    }
    // variable a is available in this scope
    console.log(a);
}

Another important problem is scope, take a look at this article at MDN var keyword. As mentioned, using let and const instead of var is the way to go.

Upvotes: 1

Related Questions