In this tutorial, you will learn about JavaScript array with the assistance of examples.
In this article, you will learn-
What is an Array?
An array is a special variable, which can hold more than one value at a time.
In JavaScript, an array is a single variable that is used to store various components. It is often used when we need to store a rundown of components and access them by a single variable. Not at all like most dialects where the array is a reference to the different variable, in JavaScript array is a single variable that stores numerous components.
As you most likely are aware, a variable can store a single component. On the off chance that you need to store numerous components immediately, you can use an array.
An array is an object that can store multiple elements. For example,
const myArray = ['hello', 'world', 'welcome'];
Create an Array
You can make an array using two different ways:
- Using an array literal
The most straightforward approach to make an array is by using an array literal []. For instance,
const array1 = ["eat", "sleep"];
- Using the new watchword
You can likewise make an array using JavaScript’s new watchword.
const array2 = new Array("eat", "sleep");
In both of the above examples, we have made an array having two components.
Note: It is prescribed to use array literal to make an array.
Here are more examples of arrays:
// empty array const myList = [ ]; // array containing number values const numberArray = [ 2, 4, 6, 8]; // array containing string values const stringArray = [ 'eat', 'work', 'sleep']; // multiple data types array const newData = ['work', 'exercise', 1, true];
You can also store arrays, functions and other objects inside an array. For example,
const newData = [ {'task1': 'exercise'}, [1, 2 ,3], function hello() { console.log('hello')} ];
Access Elements of an Array
You can access the elements inside of an array using indices (0, 1, 2 …). For example,
const myArray = ['h', 'e', 'l', 'l', 'o']; // first element console.log(myArray[0]); // "h" // second element console.log(myArray[1]); // "e"
Note: Array’s index starts with 0, not 1.
Add an Element to an Array
You can use the built-in method push() and unshift() to add a component to an array.
The push() strategy adds a component toward the finish of an array and returns the length of another array. For instance,
let dailyActivities = ['eat', 'sleep']; // add an element at the end of the array dailyActivities.push('exercise'); console.log(dailyActivities); // ['eat', 'sleep', 'exercise']
The unshift() method adds a new element to the beginning of an array and returns the new length of an array. For example,
let dailyActivities = ['eat', 'sleep']; //add an element at the end of the array dailyActivities.unshift('work'); console.log(dailyActivities); // ['work', 'eat', 'sleep', 'exercise'']
Change the Elements of an Array
You can also add elements or change the elements by accessing the index value.
let dailyActivities = [ 'eat', 'sleep']; // this will add the new element 'exercise' at the 2 index dailyActivities[2] = 'exercise'; console.log(dailyActivities); // ['eat', 'sleep', 'exercise']
Assume, an array has two components. In the event that you attempt to add a component at index 3 (fourth component), the third component will be indistinct. For instance,
let dailyActivities = [ 'eat', 'sleep']; // this will add the new element 'exercise' at the 3 index dailyActivities[3] = 'exercise'; console.log(dailyActivities); // ["eat", "sleep", undefined, "exercise"]
Essentially, on the off chance that you attempt to add components to high lists, the indices in the middle of will have vague worth.
Remove an Element from an Array
You can use the pop() strategy to eliminate the last component from an array. The pop() technique likewise returns the returned value. For instance,
let dailyActivities = ['work', 'eat', 'sleep', 'exercise']; // remove the last element dailyActivities.pop(); console.log(dailyActivities); // ['work', 'eat', 'sleep'] // remove the last element from ['work', 'eat', 'sleep'] const removedElement = dailyActivities.pop(); //get removed element console.log(removedElement); // 'sleep' console.log(dailyActivities); // ['work', 'eat']
In the event that you need to eliminate the primary component, you can use the shift() technique. The shift() technique eliminates the primary component and furthermore returns the eliminated component. For instance,
let dailyActivities = ['work', 'eat', 'sleep']; // remove the first element dailyActivities.shift(); console.log(dailyActivities); // ['eat', 'sleep']
Array length
You can discover the length of a component (the quantity of components in an array) using the length property. For instance,
const dailyActivities = [ 'eat', 'sleep']; // this gives the total number of elements in an array console.log(dailyActivities.length); // 2
Array Methods
In JavaScript, there are different array strategies accessible that makes it simpler to perform useful calculations.
A portion of the normally used JavaScript array techniques are:
Method | Description |
concat() | joins two or more arrays and returns a result |
indexOf() | searches an element of an array and returns its position |
find() | returns the first value of an array element that passes a test |
findIndex() | returns the first index of an array element that passes a test |
forEach() | calls a function for each element |
includes() | checks if an array contains a specified element |
push() | aads a new element to the end of an array and returns the new length of an array |
unshift() | adds a new element to the beginning of an array and returns the new length of an array |
pop() | removes the last element of an array and returns the removed element |
shift() | removes the first element of an array and returns the removed element |
sort() | sorts the elements alphabetically in strings and in ascending order |
slice() | selects the part of an array and returns the new array |
splice() | removes or replaces existing elements and/or adds new elements |
Example: JavaScript Array Methods
let dailyActivities = ['sleep', 'work', 'exercise'] let newRoutine = ['eat']; // sorting elements in the alphabetical order dailyActivities.sort(); console.log(dailyActivities); // ['exercise', 'sleep', 'work'] //finding the index position of string const position = dailyActivities.indexOf('work'); console.log(position); // 2 // slicing the array elements const newDailyActivities = dailyActivities.slice(1); console.log(newDailyActivities); // [ 'sleep', 'work'] // concatenating two arrays const routine = dailyActivities.concat(newRoutine); console.log(routine); // ["exercise", "sleep", "work", "eat"]
Note: If the element is not in an array, indexOf() gives -1.
Working of JavaScript Arrays
In JavaScript, an array is an object. What’s more, the indices of arrays are objects keys.
Since arrays are objects, the array components are stored by reference. Henceforth, when an array value is replicated, any adjustment in the duplicated array will likewise reflect in the original array. For instance,
let arr = ['h', 'e']; let arr1 = arr; arr1.push('l'); console.log(arr); // ["h", "e", "l"] console.log(arr1); // ["h", "e", "l"]
You can also store values by passing a named key in an array. For example,
let arr = ['h', 'e']; arr.name = 'Salman'; console.log(arr); // ["h", "e"] console.log(arr.name); // "Salman" console.log(arr['name']); // "Salman"
However, it isn’t prescribed to store values by passing subjective names in an array.
Subsequently in JavaScript, you should an array if values are in arranged assortment. In any case, it’s better to use the object with { }.
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.