Table of Contents

What Are JavaScript Objects

Code Playground is only enabled on larger screen sizes.

Objects are defined with curly braces ({}).

javascript
let obj = {};

Items in the object, which are referred to as properties, are made of key: value pairs. Different properties are separated with commas.

javascript
let obj = {
  firstName: "John",
  lastName: "Doe",
  age: 25,
};
 
console.log(obj);
text
{ firstName: 'John', lastName: 'Doe', age: 25 }

In this example, firstName: "John" is a property. firstName is the property name, and the string "John" is the property value.

The values can be any data type you want, such as numbers, BigInt, strings, Boolean values, null, undefined, arrays, functions, and even other objects.

javascript
let obj = {
  number: 100,
  bigint: 999999999999999999n,
  string: "Qwerty",
  null: null,
  undefined: undefined,
  array: [1, 2, 3],
  object: { name: "John Doe" },
  doNothing: function () {
    return null;
  },
};
 
console.log(obj);
text
{
  number: 100,
  bigint: 999999999999999999n,
  string: 'Qwerty',
  null: null,
  undefined: undefined,
  array: [ 1, 2, 3 ],
  object: { name: 'John Doe' },
  doNothing: [Function: doNothing]
}

As you can see, an object can be placed inside another object, which makes a nested structure.

A function can also be stored inside an object as its property, and in this case, the function will be referred to as a method.

Getting a property

To retrieve an object property, you can use the dot operator (.):

javascript
let obj = {
  firstName: "John",
  lastName: "Doe",
  age: 25,
};
 
console.log(obj.firstName);
console.log(obj.lastName);
console.log(obj.age);
text
John
Doe
25

Or use the square bracket syntax:

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

Doesn't this remind you of the arrays? Previously, we used the same syntax to access an array element. This is because the array is just a special type of object. The array indexes are the object keys.

There are two other similar data structures called maps and sets in JavaScript. They are both special types of objects designed for specific purposes. We will talk more about them later.

As we've mentioned before, an object can also be the property of another object, forming a nested structure. To retrieve a property, you can chain multiple dot operators or square brackets together.

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

Updating or adding a property

After getting an object property, you can change its value with the assignment operator (=).

javascript
let obj = {
  firstName: "John",
  lastName: "Doe",
  age: 25,
};
 
obj.age = 18;
 
console.log(obj);
text
{ firstName: 'John', lastName: 'Doe', age: 18 }

The same thing works for the square bracket syntax.

javascript
let obj = {
  firstName: "John",
  lastName: "Doe",
  age: 25,
};
 
obj["age"] = 18;
 
console.log(obj);
text
{ firstName: 'John', lastName: 'Doe', age: 18 }

You can also add new properties to existing objects like this:

javascript
let obj = {
  firstName: "John",
  lastName: "Doe",
  age: 25,
};
 
obj.status = "admin";
 
console.log(obj);
text
{ firstName: 'John', lastName: 'Doe', age: 25, status: 'admin' }

The property keys

We just explained that the property values can be any data type you want, but what about the keys?

Recall that when we are using the square bracket syntax, the keys must be placed inside quotation marks. Yes, even though the object keys are not enclosed inside quotation marks when we defined them, they are in fact strings.

In JavaScript, the object keys are either strings or symbols (we will explain what symbols are later), and other data types will be automatically converted into strings. For example,

javascript
let obj = {
  firstName: "John",
  lastName: "Doe",
  age: 25,
  1: "Number 1",
  null: "Null",
};
 
console.log(Object.keys(obj));
text
[ '1', 'firstName', 'lastName', 'age', 'null' ]

Object.keys() is a method that returns an array of keys in the given object. Notice that both the number 1 and null have been converted into strings. You may use the typeof operator to check their data type.

Iterating over an object

There is 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);
}

However, things are a bit more complex here. Recall that the object properties are defined in key/value pairs, and the key variable only matches the key part of the property. So this will be the output:

text
firstName
lastName
age

To access the property value, the dot operator is not going to work here, and instead, you must use the square bracket syntax.

javascript
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 object methods

There are three methods under the Object class that can be useful when working with objects. They are 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' }
  ]
]

Compare objects

One more thing we need to mention about objects is that you cannot create two objects that are equal. For instance:

javascript
let a = {
  name: "John Doe",
};
 
let b = {
  name: "John Doe",
};
 
console.log(a === b);
text
false

Even though the two objects have the exact same properties, JavaScript will still tell you they are not equal.

Two objects are only equal if they reference the same object. For example,

javascript
let a = {
  name: "John Doe",
};
 
let b = a;
 
console.log(a === b);
text
true

In this case, a and b both point to the same object, so now they are equal.

JSON

Our discussion about objects leads to another data structure called JSON. JSON is short for JavaScript Object Notation, and as the name implies, it is created based on JavaScript's object syntax. It is widely used by modern web applications to transfer data between servers and clients.

json
{
  "firstName": "John",
  "lastName": "Doe",
  "age": "25"
}

As you can see, JSON also follows the key: value format. The only thing different about JSON is that both the key and the value are strings and must be enclosed in quotation marks. JSON cannot store any other types of data.

Similarly, you can create a nested structure with JSON.

json
{
  "firstName": "John",
  "lastName": "Doe",
  "age": "25",
  "child": {
    "id": "123"
  }
}

JSON is so widely used that most programming languages, JavaScript included of course, has built-in methods to process it, allowing you to parse and read data from JSON. We'll talk about how to do it later in this course.

The symbol type

Finally, we need to talk about the symbols.

Symbol is a primitive data type most commonly used to create object keys. It is created with the Symbol() function.

javascript
let id = Symbol("id"); // The string "id" is the symbol description

And then, you can use this id as the object key.

javascript
let id = Symbol("id");
 
let obj = {
  [id]: 12345,
  firstName: "John",
  lastName: "Doe",
  age: 25,
};
 
console.log(obj);
text
{ firstName: 'John', lastName: 'Doe', age: 25, [Symbol(id)]: 12345 }

The id must be wrapped inside a pair of square brackets, or JavaScript will assume it is a plain string.

A symbol is a value guaranteed to be unique. For example, you can create two symbols with the same description, and then try to equate them;

javascript
let id1 = Symbol("id");
let id2 = Symbol("id");
 
console.log(id1 === id2);
text
false

And JavaScript will tell you that they are not equal.

Symbols are often used to hide properties. Properties defined with a symbol will be skipped in the for in loop:

javascript
let id = Symbol("id");
 
let obj = {
  [id]: 12345,
  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