DEV Community

Ranjani R
Ranjani R

Posted on

JS-OBJECTS AND ARRAYS

Hi all today I am going to tell about the two most commonly used non-primitive data types in JS which are objects and arrays.

Objects are collections of key-value pairs used to store and organize data. They allow us to group related information together, making our code more readable and structured. Each key is also known as property and their value can be of any data type. Below is an example of object:

const person = {
  name: "Ranjani",
  age: 25,
  isMarried: true,
  nationality:"Indian",
};
Enter fullscreen mode Exit fullscreen mode

From the above object we can access the individual properties in two ways and they are:

Dot Notation: person.name -> "Ranjani"
Bracket Notation: person[name]->"Ranjani"

The difference b/w both is that the dot notation is more simple and straightforward and can be used when the property/key name does not contain any spaces, starts with a letter and does not have special characters (Yes, we can have all the above in our key names too). On the other hand bracket notation can be used if we need to store our key name in a variable and access it through that. For eg:

let key=age;
person[key] -> 25
Enter fullscreen mode Exit fullscreen mode

We can also add ,delete and modify properties and its values in the object.

person.kids=2; //Creates a new property
delete person.nationality; //Deletes existing property
person.age=30; //Modifies the age property
Enter fullscreen mode Exit fullscreen mode

So this is the basic example and brief intro about the Object data type. Next up is Arrays.

Arrays is another set of non-primitive data types which is very commonly used in real life programming.

Arrays are ordered collections used to store multiple values in a single variable. Each value is called an element, and it’s accessed by its index (starting from 0).
They’re great for grouping related data—like lists, sets of items, or results from a function. Eg:

const colors = ["red", "green", "blue"];

Enter fullscreen mode Exit fullscreen mode

We can access the values like this:

  • colors[0] → "red"
  • colors[1] → "green"

where 0 and 1 are the index of the array. Arrays have the following methods through which we can add and delete values:

colors.push("yellow");     // Add to end of the array
colors.pop();              // Remove last item from the array
colors.unshift("purple");  // Add to start of the array
colors.shift();            // Remove first item
Enter fullscreen mode Exit fullscreen mode

We can also loop through the array using for loop and print the values one by one. We can also store objects into arrays and use it.

So that's all regarding arrays. Hope this post is useful to all. See you all in the next post.

Top comments (0)