Search code examples
javascriptfor-looprangeincrement

Increment a number between 2 values and also process the limit of the range


How can I easily increment a number between 2 values (e.g. 0 and 10) by a given step (e.g. 3) and process also the limits of the range ? All numbers could be integers or floats. I was thinking of using a for-loop with an increment of 3, but then I will not have the value 10 :

for(i=0; i<=10; i=i+3){
  // Do something with i
}

Data that shall be processed inside the loop: 0, 3, 6, 9, 10


Solution

  • You could limit the upper bound with Math.min.

    const
        step = 2.7;
    
    for (let i = 0, l = Math.ceil(10 / step); i <= l; i++) {
        const value = Math.min(i * step, 10);
        console.log(value);
    }