What is Array?
The array is a variable that contains more than one value at a time. In JavaScript, we can declare an array variable as shown below:
var arrayName = ["value1", 1, 2, "value4",...]
How to access the array values?
An array can consist of any of the values at a time as shown above. If we want to print this array values altogether, we can write:
document.write(arrayName); //This will print - value1,1,2,value4
Array values have indexes which starts from 0 and we can access each of the array values from those indexes as shown below:
document.write(arrayName[0]); //This will print - value1
document.write(arrayName[1]); //This will print - 1
document.write(arrayName[2]); //This will print - 2
...and so on....
Iterating Array
We have seen how to access the array values, specifying their indexes. For accessing all the array values we can iterate through them individually with the help of loops as shown in the below image:
Iterating array values |
Inserting value in an Array
To insert any value in an array, push() method is used. In our example, if we want to insert a string "value5", we need to write the below code:
arrayName.push("value5");
Removing value from an Array
We have 3 methods in JavaScript for that. They are:
- splice(index, number of items to be deleted from the index mentioned) - The splice method has 2 arguments - index and number of items to be deleted. In our example, if we want to delete the value1, we can write arrayName.splice(0,1). This will start removing 1 element from index 0 of the array, arrayName.You can try the below code and see how it works for different index values and numbers.
- shift() - Shift method removes the first value from the array
- pop() - Pop method removes the last value from the array
Here, is the JSFiddle example URL for your reference: JSFiddle Example
Updating an array value
To update array values, we can again use the splice() method.
Splice method deletes a value but the values that need to be replaced can be added as a parameter to the splice method. In our example, if we want to change the "value1" to "Changed Value1", we can do that using the splice method as shown below:
Here, if we want to update the second & third value of arrayName with 10, 14, we can write the below code for that.
I hope this article is useful to understand and remember arrays and some common array operations. For any queries, you can write to me at [email protected]. To get notified for the releases, subscribe through email. If you found this article useful, please share it. Thank you 😊.