How to properly iterate over an array in JavaScript: forEach, for, for...of and other ways
Hello everyone! I just started learning JavaScript and can't figure out array iteration. I have a simple array with user names:
const users = ['Anna', 'Ivan', 'Maria', 'Petr'];
I need to output each name to the console. I tried using a regular for loop, but I keep getting confused with indices and array length. For example, I write:
for (let i = 0; i <= users.length; i++) {
console.log(users[i]);
}
And at the end I get undefined. Why does this happen? I've heard there is a forEach method, but I don't understand how it works and how it differs from regular for. I've also seen some for...of and for...in, but I'm completely confused.
Please tell me which method is best to use for iterating over an array in modern JavaScript?