What Are JavaScript Objects

Code Playground is only enabled on larger screen sizes.

Similar to the for...of loop which allows us to iterate over all items in the array. There is also a special for...in loop for iterating over an object. The syntax is as follows:

javascript
let obj = {
  firstName: "John",
  lastName: "Doe",
  age: 25,
};
 
for (let key in obj) {
  console.log("key: " + key);
  console.log("value: " + obj[key]);
}
text
key: firstName
value: John
key: lastName
value: Doe
key: age
value: 25

The variable key matches the property names, and you can access the corresponding value using obj[key].

The dot operator is not going to work here, you must use the square bracket syntax.

There are also three methods under the Object class that can be useful when working with objects: Object.keys(), Object.values(), and Object.entries().

  • Object.keys()

This method returns an array of keys in the given object.

javascript
let obj = {
  firstName: "John",
  lastName: "Doe",
  age: 25,
  contactInfo: {
    phone: 1234567890,
    email: "something@example.com",
  },
};
 
console.log(Object.keys(obj));
text
[ 'firstName', 'lastName', 'age', 'contactInfo' ]
  • Object.values()

This method returns an array of values in the given object.

javascript
let obj = {
  firstName: "John",
  lastName: "Doe",
  age: 25,
  contactInfo: {
    phone: 1234567890,
    email: "something@example.com",
  },
};
 
console.log(Object.values(obj));
text
[
  'John',
  'Doe',
  25,
  { phone: 1234567890, email: 'something@example.com' }
]
  • Object.entries()

Return all key/value pairs in an array.

javascript
let obj = {
  firstName: "John",
  lastName: "Doe",
  age: 25,
  contactInfo: {
    phone: 1234567890,
    email: "something@example.com",
  },
};
 
console.log(Object.entries(obj));
text
[
  [ 'firstName', 'John' ],
  [ 'lastName', 'Doe' ],
  [ 'age', 25 ],
  [
    'contactInfo',
    { phone: 1234567890, email: 'something@example.com' }
  ]
]