How to iterate over all array elements in JavaScript? All methods with examples
Hello everyone! I just started learning JavaScript and encountered this problem: I have an array with user names, and I need to output each name to the console or insert it into an HTML list. I know I can use a regular `for` loop, but I've heard there are other ways — `forEach`, `for...of`, `map`. I'm completely confused about which one is better and when to use what.\n\nHere's an example of my code:\n\n```javascript\nconst users = ['Anna', 'Ivan', 'Maria', 'Petr'];\n// I need to output: "Hello, Anna!", "Hello, Ivan!" etc.\n```\n\nI tried writing it like this:\n\n```javascript\nfor (let i = 0; i < users.length; i++) {\n console.log('Hello, ' + users[i] + '!');\n}\n```\n\nThis works, but the code looks bulky. I've heard there's a `forEach` method, but I don't understand how to use it correctly.
No answers yet.
Log in to leave an answer