In the example above, as you can see there are 10 numbers in the array. The length of the array is 10 however in order to extract any value for e.g. 60, a developer has to use the index value for that element which is 5 considering the index value starts at 0.
new Array(), but you can use
. Both statements will create an empty array.
Let’s take a look at an example. As seen below, the
length of the array can be figured out by using the
length property on the array itself. In order to access a particular element from the array, use it’s index value inside of the square brackets. An item can be changed in an array by reassigning it a new value using the equal sign
const grades = [50, 78, 94, 65, 79, 82, 100, 91]; console.log(grades.length); // prints 8 // access the value 79 using its index value console.log(grades); // prints 79. Index starts at 0. // change value at index 0 from 50 to be 86 grades = 86 console.log(grades); // prints [86, 78, 94, 65, 79, 82, 100, 91]
Arrays provide some useful and efficient built-in methods. Here is a MDN Documentation on Arrays and its methods. We will explore the most commonly used methods listed below:
Array Push or Add Array Elements
An array element can easily be added to an existing array by using
push(). This method will add one or more elements to the end of the array and return the length of the new array for future use.
const grades = [50, 78, 94, 65, 79, 82, 100, 91]; console.log(grades.length); // prints 8 // add 86 to the end of grades array // returns new length of the array const newGradesLength = grades.push(86); console.log(grades); // prints [50, 78, 94, 65, 79, 82, 100, 91, 86] console.log(newGradesLength); // 9
Array Pop or Remove Elements from an Array
An element can easily be removed from an existing array by using
pop(). This method will remove an element from the end of the array and return that element.
const grades = [50, 78, 94, 65, 79, 82, 100, 91]; console.log(grades.length); // prints 8 // remove last element 91 from the end of grades array const lastElement = grades.pop(); console.log(grades); // prints [50, 78, 94, 65, 79, 82, 100] console.log(grades.length); // 7 console.log(lastElement); // 91
includes() method is very useful to find if a certain element exists in the array. It returns
false indicating whether the element was found or not.
const grades = [50, 78, 94, 65, 79, 82, 100, 91]; console.log(grades.includes(86)); // prints false console.log(grades.includes(91)); // prints true
indexOf() method is very useful to find if a certain element exists in the array and if so, at what index it was found. If an element is not found, the index returned will be
const grades = [50, 78, 94, 65, 79, 82, 100, 91]; console.log(grades.indexOf(86)); // prints -1 console.log(grades.indexOf(91)); // prints 7
Get hands-on experience writing code with interactive tutorials in our free online learning platform.
- Free and fun
- Designed for beginners
- No downloads or setup required