let colors = ['Red', 'Green', 'Blue'];
for (const [index, color] of colors.entries()) {
console.log(`${color} is at index ${index}`);
}Code language: JavaScript (javascript)
const array = ['a', 'b', 'c', 'd'];
for (const item of array) {
console.log(item)
}
// Result: a, b, c, d
const string = 'Ire Aderinokun';
for (const character of string) {
console.log(character)
}
// Result: I, r, e, , A, d, e, r, i, n, o, k, u, n
const letters = ["a","b","c", "d", "e","f"];
for (const x of letters) {
console.log(x)
}
/*note that for of only works for iterable objects(which includes an array). The above type of code would NOT work for a JSON for example*/
/*for example for something like
const x = {0:0, 1:2222, 2:44444}, you can only use for ... in as JSON is not an iterable*/
let list = ["a", "b", "c"];
// for in
for (let i in list) {
// i is index
console.log(i); // "0", "1", "2",
console.log(list[i]); // "a", "b", "c"
}
// for of
for (let i of list) {
// i is value
console.log(i); // "a", "b", "c"
}