Why during run time Js get messy

73 views Asked by At

I was doing a function to toggle up between CSS classes for an HTML element using a clases object with 2 properties, active and non-active and a global variable count to keep track the run times. I realize some strange JS behavior:

Here it goes fine, in the console output I get the toggle effect

function toogleClases() {
    if(count%2==0){
        return clases.active;
    }
    else{
        return clases.non_active;
    }
}
for(let i = 0 ; i < 10 ; i++){
    console.log(toogleClases());
    count++;
}

but if I insert the count++ into the toogle function itself ( what i think is more practical)

function toogleClases() {
    if(count%2==0){
        return clases.active;
    }
    else{
        return clases.non_active;
    }
    count++;
}

for(let i = 0 ; i < 10 ; i++){
    console.log(toogleClases());
}

i get always the same value on the console '10 times : active' , i will love to know why this happen, i suspect that it is a weird Js part

3

There are 3 answers

0
Angelotti On

You don't need a counter you can pass i as parameter:

 function toogleClases(count) {
    if(count%2==0){
        return clases.active;
    }
    else{
        return clases.non_active;
    }

}

for(let i = 0 ; i < 10 ; i++){
    console.log(toogleClases(i));
}
0
Casper On

Your function return output before update the count variable. anything after return statement does not trigger so your count value is always 0. you need to update count++ before return the output.

var count = 0;
function toogleClases() {
   
    let status = false;
    if(count%2 == 0){
        status = true;
    } 
    
    count++;
    return status ? 'active' : 'non active';
    //replace 'active' with clases.active and 'non active' with  clases.non_active
   
}

for(let i = 0 ; i < 10 ; i++){
    console.log(toogleClases());
}

0
Ivanhoe Cheung On

Because you're calling count++ after toogleClases() returns, count++ will never be reached. Try this instead:

function toogleClases() {
    if(count%2==0){
        count++;
        return clases.active;
    }
    else{
        count++;
        return clases.non_active;
    }

}

for(let i = 0 ; i < 10 ; i++){
    console.log(toogleClases());
}