4

Modifying Array Data with Indices

 2 years ago
source link: https://dev.to/swarnaliroy94/modifying-array-data-with-indices-3d71
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Basic Data Structure in JavaScript : Arrays (3 Part Series)

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 modeExit 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 modeExit 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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK