How can I write this javascript loop better way

I have this JS code

if (parseInt(counter.text(), 10) > 0) {
    counter.text(parseInt(counter.text(), 10) - 1);
}

if (parseInt(counter.text(), 10) < 1) {
    counter.attr('data-active', true);
}

This just checks if the count is > 0 then decrement it and if after decrementing == 0 then hide it.

I am looking for some better way to write it. I always get caught in code review about non efficient coding 😉

Answer

I think this will give you the same behavior, without spending as much time parsing.

var value = parseInt(counter.text(), 10);
if(value > 0) {
    value--;
    counter.text(value);
}
if(value < 1) {
    counter.attr('data-active', true);
}
  • Create a variable to hold the result of parsing. This reduces repetition of code, as well as avoiding doing the same work over and over.
  • You were reducing the value found in counter.text() prior to checking the value, so I’m reducing the value of the variable to preserve the same behavior.

Note that you probably can improve the performance of your loop even better, but you haven’t included your loop in the OP.

Leave a Reply

Your email address will not be published. Required fields are marked *