JavaScript Data Structures

Basic How-tos for JS Objects

Rakesh Ghatvisave
JS for Noobs
3 min readFeb 9, 2022

--

JS Objects are represented in the following format:

property : value

We will use the following Object example to run our how-tos:

Object rendering in JS Console

If you copy-paste this Object in a JavaScript Console and access the variable appleFounder1, it will render as:

Basic How-Tos with JS Objects

How to access the value of a key-value pair inside an object?

Use the name of the variable in which the Object is placed followed by a dot notation, followed by the name of the key.

Example

In the above Object example, if you want to access the value of the name property, run:

Output:

How to add a new property/key-value pair to an existing Object?

To add a new property to an existing Object:

  1. Type the name of the variable under which the Object is placed.
  2. After the name of the variable, insert a dot notation, followed by the name of the new key.
  3. Use = and then add the new value to the key whether it’s a string or an integer value.

Example

In the above Object example, let’s say we want to add a new property called nemesis,:

appleFounder1.nemesis = “John Sculley”;

Output:

The new property nemesis is added. To verify if this property is added, access the variable appleFounder1 and check the new entry to the Object.

New property nemesis added to the Object

How to change the value of a property inside an Object?

To change an existing value of a property:

  1. Reference the variable name, followed by the dot notation.
  2. Use = and then enter the new value for the property.

Example

In the main Object example, let’s say you want to change the isMarried property value to false, run:

appleFounder1.isMarried = false;

Output

appleFounder1.isMarried = false;
false

The property valued is changed to false. To verify, access the variable appleFounder1 and check the value of the isMarried property.

Console Output

Property value for isMarried changed to false

How to access array values within an object?

  1. Use the variable name, followed by the dot notation, followed by the array name, and finally the bracket notation.
  2. Inside the bracket notation[], reference the index value of the array you want to access.

Example
In the main Object example, there is an array of inventions. Let’s say you want to access the index 0 value which is iphone:

appleFounder1.inventions[0]

Output

appleFounder1.inventions[0]
‘iphone’

How to use a JS function inside an Object?

To add a function inside an Object:

  1. Add a new property and assign a function to the new property.

To invoke/call the function:

appleFounder1.keynoteintro();

The browser will display “Today we are going to change the world”

Note: A FUNCTION INSIDE AN OBJECT IS A METHOD

  • Keynoteintro is a method of appleFounder1

--

--

Rakesh Ghatvisave
JS for Noobs

Technical Writer|UX Writer. Delightfully entrenched in Hong Kong!