Array in Javascript
In JavaScript, an array is a collection of values that are stored in a single variable. Arrays are created using square brackets, and the values inside the brackets are each separated by commas. In JavaScript array is a non-primitive datatype. It can be modified and is mutable.
Here's an example of an array that contains 4 elements:
let myArray = [1, 2, 3, 4];
You can access the elements of an array using their indexes. The index of the first elements starts from 0 and so on.
Here's an example of how to access the second element of the array:
let myArray = [1, 2, 3];
let secondElement = myArray[1]; // secondElement is now 2
There are many methods available for working with arrays, such as push
and pop
for adding and removing elements, shift
and unshift
for adding and removing elements from the beginning of the array, and sort
for sorting the elements.
Array Methods in JavaScript :
Here is a list of some of the most commonly used methods for working with arrays in JavaScript:
push
: adds one or more elements to the end of an array and returns the new length of the array.pop
: removes the last element from an array and returns the value of that element.shift
: removes the first element from an array and returns the value of that element.unshift
: adds one or more elements to the beginning of an array and returns the new length of the array.concat
: combines two or more arrays and returns a new array.slice
: returns a shallow copy of a portion of an array.splice
: adds or removes elements from an array.sort
: sorts the elements of an array in place and returns the sorted array.reverse
: reverses the order of the elements of an array in place and returns the reversed array.indexOf
: returns the index of the first occurrence of a specified element in an array, or -1 if the element is not present.lastIndexOf
: returns the index of the last occurrence of a specified element in an array, or -1 if the element is not present.forEach
: executes a provided function once for each array element.map
: creates a new array with the results of calling a provided function on every element in the array.filter
: creates a new array with all elements that pass the test implemented by a provided function.reduce
: applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.The
some()
method in JavaScript is used to test whether at least one element in an array passes a test implemented by a provided function. It returns a Boolean value oftrue
if the provided function returnstrue
for at least one element in the array, andfalse
if it returnsfalse
for all elements.The
find()
method in JavaScript is used to return the value of the first element in an array that satisfies a provided testing function. If no element passes the test, thefind()
method returnsundefined
.