Course Content
Introduction to JavaScript
Introduction to JavaScript
Array Methods
Arrays are versatile for storing and retrieving data. Retrieving data using square brackets []
is called indexing.
However, there are various methods available for working with arrays.
Adding Elements
There are different ways to add elements to an array.
Push
The push()
method adds a new value to the end of the array:
let arr = [1, 2, 3]; arr.push(4); arr.push(5); arr.push(6); console.log(arr);
Unshift
The unshift()
method works like the push()
method, but it inserts the value at the beginning of the array.
let arr = [1, 2, 3]; console.log("Array:", arr); arr.unshift(222); // Insert element at the start console.log("Array:", arr);
Indexing
You can append a new value by indexing:
let arr = [1, 2]; arr[2] = 3; arr[3] = 4; console.log(arr);
Indexing allows you to assign a value to a specified index, reassign a previous value, and more:
let arr = [1, 2, 3]; arr[0] = 4; console.log("Array:", arr);
To create a new element in the array without mistakes, you can use the push(value)
method or the arr[arr.length] = value
expression:
let myArray = []; myArray[myArray.length] = "indexing"; console.log("After first indexing:", myArray); myArray.push("pushing"); console.log("After first pushing:", myArray); myArray[myArray.length] = "indexing"; console.log("After second indexing:", myArray); myArray.push("pushing"); console.log("After second pushing:", myArray);
Deleting Elements
Sometimes, you may need to delete elements from an array. This can be done in different ways.
Pop
The pop()
method deletes the last element in an array and allows you to save it to another variable:
let arr = [11, 22, 33, 44]; console.log("Array:", arr); let x = arr.pop(); // Remove and save the last element in `arr` to variable `x` console.log("Popped element:", x); console.log("Array now:", arr);
Shift
The shift()
method works like pop()
, but it removes the first element from an array:
let arr = [11, 22, 33, 44, 55, 66]; console.log("Array:", arr); let popped = arr.pop(); // Remove the last element console.log("Popped:", popped); console.log("Array:", arr); let shifted = arr.shift(); // Remove the first element console.log("Shifted:", shifted); console.log("Array:", arr);
Thanks for your feedback!