Below JavaScript loop for increment is working, but for decrement not. How to solve this?
for(var i=1; i<5; i++) { alert(i); } work fine
for(var i=10; i<5; i--) { alert(i); } not working
The second parameter of the 'for' loop is the exit condition. The code in the for loop is executed as long the condition is true. For example:
for(var i = 0; i < 10; i++){
console.log([i]);
}
i is less than 10 (i < 10) which is true because in the first instance i = 0, as a result the loop goes into the code block and runs the code then increments and continues until the exit condition is no longer true.for (var i = 10; i < 5; i--){alert[i]} the code in the for loop is never executed because the exit condition i < 5 evaluates to false (i is equal to 10). To achieve your goal you've to change the exit condition for the for loop as:
for (var i = 10; i > 5; i--) {
alert([i]);
}
You can make it more dynamic by setting i to the length of what you are iterating through:
const string = "abcd";
for (let i = string.length; i > 0; i--) {
console.log(str[i]);
}
Notice: if you set the condition to i >= 0 you will be ignoring the last element in the array or string as it's 0 indexed base.
i > 0 that will be ignoring 0 indexThis is how reverse loops should be used (at least for this case):
const string = "abcd";
// first of all, `string[string.length]` will always be undefined
// you can't access what is not there, because the string is zero-base indexed
// so... we initialize a `len` const at `string.length - 1`
const len = string.length - 1;
// we loop in reverse
for(let i = len; i >= 0; i--){
// but... it doesn't mean we can't read the characters
// in an ascending order
const char = string[len - i];
// no more undefined
// and this will print `a`, `b`, `c`, `d`
console.log(char);
}
iis never less than 5. The for loop accepts 3 (optional) conditional statements. All of which must be truthy. Sincei<5is false on the first iteration, it causes execution to skip to first expression after the for loop. More Info