Let's assume that I have a code structure as below,
const fruits = [ `apple`, `banana`, `orange` ];
for ( let i = 0; i < fruits.length; i++ ) {
const res = fruits[ i ];
console.log ( res ); // apple banana orange
}
I want to destructure the
const res = fruits[ i ];
Is it possible and I can use forEach to achieve the destructuring but I want to achieve the same using the for loop.
Thanks in advance.
PS: using forEach or for..in it can be done but I want to get same destructuring within the for loop.
If you absolutely want to keep the classic for
loop:
const fruits = [`apple`, `banana`, `orange`];
for (let i = 0; i < fruits.length; i++) {
const { [i]: res } = fruits;
console.log(res); // apple banana orange
}
As a shorter syntax, for..of
works with iterable objects (like arrays).
You can use it like this:
const fruits = [`apple`, `banana`, `orange`];
for (const fruit of fruits) {
console.log(fruit); // apple banana orange
}
To go further, you can even use destructuring in a for..of
loop (e.g: to retrieve the string lengths):
const fruits = [`apple`, `banana`, `orange`];
for (const { length } of fruits) {
console.log(length); // 5 6 6
}