DEV Community 👩‍💻👨‍💻

Swarnali Roy
Swarnali Roy

Posted on • Updated on

Modifying Array Data with Indices

In this episode of the series, let's learn How to Modify Array Data with Indices.

In addition to accessing array data with index, we can also modify them with the same square bracket [] notation. We can set an index with a new value replacing the existing one, with the same notation.

For Example:

let numArr = [50,60,70];
numArr[1] = 20;
console.log(numArr[1]); //output: 20
console.log(numArr); //output: [50,20,70]
Enter fullscreen mode Exit fullscreen mode

In the above example, the value of the index 1 is assigned to the value 20. If we see the console, we will notice that index 1 is now holding the new value 20, replacing the initial value 60. The numArr is holding the value [50,20,70]

Let's see another easy example to modify the same array. In this example, we will add a new index with a new value in the existing array , with the same notation. The new index with new value will be added at the end of the array.

let numArr = [50,60,70];
numArr[3] = 80;
console.log(numArr[3]); //output: 80
console.log(numArr); //output: [50,60,70,80]
Enter fullscreen mode Exit fullscreen mode

We can notice that, the array is initialized with three indices 0,1 and 2 holding the value, 50,60 and 70 respectively. Here, numArr[3] simply added a fourth index to the array assigned with a value of 80. Now if we see the console, the numArr is holding the value [50,60,70,80], adding the fourth index with the value 80.

In the next episode, we will discuss about other methods to modify an array by adding or removing it's elements.

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.