What Are JavaScript Objects

Objects are defined with curly braces ({}).

javascript
1let obj = {};

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

javascript
1let obj = {
2  firstName: "John",
3  lastName: "Doe",
4  age: 25,
5};
6
7console.log(obj);
text
1{ 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
1let obj = {
2  number: 100,
3  bigint: 999999999999999999n,
4  string: "Qwerty",
5  null: null,
6  undefined: undefined,
7  array: [1, 2, 3],
8  object: { name: "John Doe" },
9  doNothing: function () {
10    return null;
11  },
12};
13
14console.log(obj);
text
1{
2  number: 100,
3  bigint: 999999999999999999n,
4  string: 'Qwerty',
5  null: null,
6  undefined: undefined,
7  array: [ 1, 2, 3 ],
8  object: { name: 'John Doe' },
9  doNothing: [Function: doNothing]
10}

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
1let obj = {
2  firstName: "John",
3  lastName: "Doe",
4  age: 25,
5};
6
7console.log(obj.firstName);
8console.log(obj.lastName);
9console.log(obj.age);
text
1John
2Doe
325

Or use the square bracket syntax:

javascript
1let obj = {
2  firstName: "John",
3  lastName: "Doe",
4  age: 25,
5};
6
7console.log(obj["firstName"]);
8console.log(obj["lastName"]);
9console.log(obj["age"]);
text
1John
2Doe
325

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
1let obj = {
2  firstName: "John",
3  lastName: "Doe",
4  age: 25,
5  contactInfo: {
6    phone: 1234567890,
7    email: "something@example.com",
8  },
9};
10
11console.log(obj["contactInfo"]["phone"]);
12console.log(obj.contactInfo.email);
text
11234567890
2something@example.com

Updating or adding a property

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

javascript
1let obj = {
2  firstName: "John",
3  lastName: "Doe",
4  age: 25,
5};
6
7obj.age = 18;
8
9console.log(obj);
text
1{ firstName: 'John', lastName: 'Doe', age: 18 }

The same thing works for the square bracket syntax.

javascript
1let obj = {
2  firstName: "John",
3  lastName: "Doe",
4  age: 25,
5};
6
7obj["age"] = 18;
8
9console.log(obj);
text
1{ firstName: 'John', lastName: 'Doe', age: 18 }

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

javascript
1let obj = {
2  firstName: "John",
3  lastName: "Doe",
4  age: 25,
5};
6
7obj.status = "admin";
8
9console.log(obj);
text
1{ 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
1let obj = {
2  firstName: "John",
3  lastName: "Doe",
4  age: 25,
5  1: "Number 1",
6  null: "Null",
7};
8
9console.log(Object.keys(obj));
text
1[ '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
1let obj = {
2  firstName: "John",
3  lastName: "Doe",
4  age: 25,
5};
6
7for (let key in obj) {
8  console.log(key);
9}

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
1firstName
2lastName
3age

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

javascript
1for (let key in obj) {
2  console.log("key: " + key);
3  console.log("value: " + obj[key]);
4}
text
1key: firstName
2value: John
3key: lastName
4value: Doe
5key: age
6value: 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
1let obj = {
2  firstName: "John",
3  lastName: "Doe",
4  age: 25,
5  contactInfo: {
6    phone: 1234567890,
7    email: "something@example.com",
8  },
9};
10
11console.log(Object.keys(obj));
text
1[ 'firstName', 'lastName', 'age', 'contactInfo' ]
  • Object.values()

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

javascript
1let obj = {
2  firstName: "John",
3  lastName: "Doe",
4  age: 25,
5  contactInfo: {
6    phone: 1234567890,
7    email: "something@example.com",
8  },
9};
10
11console.log(Object.values(obj));
text
1[
2  'John',
3  'Doe',
4  25,
5  { phone: 1234567890, email: 'something@example.com' }
6]
  • Object.entries()

Return all key/value pairs in an array.

javascript
1let obj = {
2  firstName: "John",
3  lastName: "Doe",
4  age: 25,
5  contactInfo: {
6    phone: 1234567890,
7    email: "something@example.com",
8  },
9};
10
11console.log(Object.entries(obj));
text
1[
2  [ 'firstName', 'John' ],
3  [ 'lastName', 'Doe' ],
4  [ 'age', 25 ],
5  [
6    'contactInfo',
7    { phone: 1234567890, email: 'something@example.com' }
8  ]
9]

Compare objects

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

javascript
1let a = {
2  name: "John Doe",
3};
4
5let b = {
6  name: "John Doe",
7};
8
9console.log(a === b);
text
1false

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
1let a = {
2  name: "John Doe",
3};
4
5let b = a;
6
7console.log(a === b);
text
1true

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
1{
2  "firstName": "John",
3  "lastName": "Doe",
4  "age": "25"
5}

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
1{
2  "firstName": "John",
3  "lastName": "Doe",
4  "age": "25",
5  "child": {
6    "id": "123"
7  }
8}

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
1let id = Symbol("id"); // The string "id" is the symbol description

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

javascript
1let id = Symbol("id");
2
3let obj = {
4  [id]: 12345,
5  firstName: "John",
6  lastName: "Doe",
7  age: 25,
8};
9
10console.log(obj);
text
1{ 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
1let id1 = Symbol("id");
2let id2 = Symbol("id");
3
4console.log(id1 === id2);
text
1false

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
1let id = Symbol("id");
2
3let obj = {
4  [id]: 12345,
5  firstName: "John",
6  lastName: "Doe",
7  age: 25,
8};
9
10for (let key in obj) {
11  console.log("Key: " + key);
12  console.log("Value: " + obj[key]);
13}
text
1Key: firstName
2Value: John
3Key: lastName
4Value: Doe
5Key: age
6Value: 25