Implementing this solution, I aim to construct a for-loop that can operate regardless of whether the starting value is higher or lower than the ending value:
function calculateRange(startVal, endVal) {
var val = startVal;
for (var step = val > endVal ? -1 : +1; val !== endVal; val += step){
// Perform actions with each value
console.log(val);
}
}
let startVal = 6;
let endVal = 3;
calculateRange(startVal, endVal);
Due to the use of val !== endVal
in defining the for-loop (which appears necessary to make the loop direction-agnostic), the final value is not counted in the iteration process. Thus, in this scenario, the output appears as follows:
6
5
4
However, it is desired to include the final value endVal
. Is there a method to integrate it within the for-loop, or is it essential to add it separately like so:
function calculateRange(startVal, endVal) {
var val = startVal;
for (var step = val > endVal ? -1 : +1; val !== endVal; val += step){
//doSomething(val);
console.log(val);
}
}
let startVal = 6;
let endVal = 3;
calculateRange(startVal,endVal);
//doSomething(endVal);
console.log(endVal);