+ 2
why this code is NOT correct?
let obj = [1,5,8]; for (let v in obj) { console.log(v); }
2 Answers
+ 4
Bilal LAIB , if you need to print each value in the array you should use for... of loop, instead of for... in which iterates through the indexes.
0
There are different ways to iterate through objects/arrays. Some of these ways are:
- Using Object
Values:
let myArray = [1,5,8];
Object.values(myArray).forEach(Value => {
console.log(Value) // Logs: 1, 5, and 8.
});
Keys:
let myArray = [1,5,8];
Object.keys(myArray).forEach(Key => {
console.log(Key) // Logs: 0, 1, and 2.
});
- For loops:
let myArray = [1,5,8];
for (let Index=0;Index < myArray.length;++i) {
let Value = myArray[Index];
console.log(Index, Value) --> Logs: (0, 1), (1, 5), (2, 8)
}
my "explanation" is pretty bad, but I hope you get the point of it.



