How to properly iterate over object properties in JavaScript?
Hello everyone! I've just started learning JavaScript and ran into a problem. I have an object with user data, and I need to output all its properties and values to the console or to the page. I'm used to working with arrays, where I use a `for` loop or `forEach`, but with objects it doesn't work the same way.
Here's an example of my object:
```javascript
const user = {
name: 'Anna',
age: 25,
city: 'Moscow',
isAdmin: false
};
```
I tried doing this:
```javascript
for (let i = 0; i < user.length; i++) {
console.log(user[i]);
}
```
But it doesn't work — `user.length` returns `undefined`. Then I tried `forEach`:
```javascript
user.forEach((value, key) => console.log(key, value));
```
And got an error: `user.forEach is not a function`. I'm stuck. Please advise.
No answers yet.
Log in to leave an answer
Blogs