How to use square bracket notations In Javascript

Square brackets are used in JavaScript primarily for accessing arrays but they can also be used for accessing or for creating nested objects in JavaScript. Here is an explanation for creating and then accessing nested objects in java script.

Example: This example shows creating nested objects using square brackets notations.

Javascript




// Declare and initialize the keys
let OuterObj = {};
const firstKey = 'key01';
const secondKey = 'key02';
const nestedFirstKey = 'nestedKey01';
const nestedSecondKey = 'nestedKey02';
 
// Assign values to the keys
OuterObj[firstKey] = 'First Key Value';
OuterObj[secondKey] = {};
OuterObj[secondKey][nestedFirstKey] = 'First Nested Value';
OuterObj[secondKey][nestedSecondKey] = 'Second Nested Value';
 
// Output
console.log(OuterObj);


Output

{
  key01: 'First Key Value',
  key02: {
    nestedKey01: 'First Nested Value',
    nestedKey02: 'Second Nested Value'
  }
}

How to Create a Nested Object in JavaScript ?

JavaScript allows us to create objects having the properties of the other objects this process is called as nesting of objects. Nesting helps in handling complex data in a much more structured and organized manner by creating a hierarchical structure.

These are the different methods to create nested objects in JavaScript are as follows:

Table of Content

  • Using object literals
  • Using square bracket notations
  • Using factory function
  • Using Object.create() method
  • Using object constructor
  • Using JavaScript classes

Similar Reads

Using object literals

JavaScript allows us to create and define the objects using curly braces { } which are called object literals. These objects’ literals have key-value pairs where identifiers or strings are the keys and the value can be of any data type be it object, string, number, etc....

Using square bracket notations

...

Using factory function

Square brackets are used in JavaScript primarily for accessing arrays but they can also be used for accessing or for creating nested objects in JavaScript. Here is an explanation for creating and then accessing nested objects in java script....

Using Object.create() method

...

Using object constructor

We can also create nested objects in javaScript by using factory function so as to define the objects and their organised nested structure....

Using JavaScript classes

...