---
title: "JavaScript – Arrays"
url: https://khanwaseem.com/blog/course/javascript-arrays
author: "khan Waseem"
published: 2023-10-02
updated: 2023-10-02
topics: ["course", "Javascript Tutorial"]
description: "Explore the world of JavaScript arrays: Learn how to create, manipulate, and work with collections of data using built-in methods and properties."
---

# JavaScript – Arrays

In JavaScript, there isn’t an “Arrays Object” per se; instead, arrays are a fundamental data structure used for storing collections of data. However, JavaScript provides an extensive set of built-in methods and properties for working with arrays efficiently.

Here’s a brief overview of how arrays work in JavaScript:

Table of Contents

[Toggle](#)

- [Syntax :](#syntax)
- [Array Properties :](#array-properties)
- [Array Methods :](#array-methods)
- [Adding and Removing Elements](#adding-and-removing-elements)[push() and pop()](#push-and-pop)
- [shift() and unshift()](#shift-and-unshift)

- [Combining and Extracting Arrays](#combining-and-extracting-arrays)[concat()](#concat)
- [slice()](#slice)

- [Iterating through Arrays](#iterating-through-arrays)[forEach()](#foreach)

- [Transforming Arrays](#transforming-arrays)[map()](#map)
- [filter()](#filter)

- [Searching and Finding Elements](#searching-and-finding-elements)[find()](#find)
- [findIndex()](#findindex)

- [Array Data Validation](#array-data-validation)[some() and every()](#some-and-every)

- [Reducing Arrays](#reducing-arrays)[reduce() and reduceRight()](#reduce-and-reduceright)

- [Sorting and Reversing](#sorting-and-reversing)[sort()](#sort)
- [reverse()](#reverse)

- [Checking for Element Existence](#checking-for-element-existence)[includes(), indexOf(), and lastIndexOf()](#includes-indexof-and-lastindexof)

- [Conclusion](#conclusion)

## Syntax :

 You can create an array by enclosing a list of values within square brackets `[]`.

```javascript
let fruits = ['apple', 'banana', 'cherry'];Code language: JavaScript (javascript)
```

## Array Properties :

In JavaScript, arrays are versatile data structures used to store collections of items. While they are not objects in themselves, they have properties that provide useful information about the array’s characteristics and elements. Here are some essential array properties:

**1. `length` Property**:

- The `length` property returns the number of elements in an array.

- Example:

```javascript
let colors = ["red", "green", "blue"];
let numberOfColors = colors.length; // 3Code language: JavaScript (javascript)
```

**2. `constructor` Property**:

- The `constructor` property refers to the constructor function that created the array.

- Example:

```javascript
let numbers = [1, 2, 3];
console.log(numbers.constructor); // Output: [Function: Array]Code language: JavaScript (javascript)
```

**3. `prototype` Property**:

- The `prototype` property allows you to add properties and methods to all instances of an array, enhancing its behavior.

- Example:

```javascript
Array.prototype.sum = function() {
   return this.reduce((total, current) => total + current, 0);
};

let myArray = [1, 2, 3, 4, 5];
let sum = myArray.sum(); // 15Code language: JavaScript (javascript)
```

**4. `Symbol.species` Property**:

- The `Symbol.species` property is used for specifying the constructor function that is used to create derived array objects.

- Example:

```javascript
class MyArray extends Array {}
MyArray[Symbol.species] = Array;

let customArray = new MyArray(1, 2, 3);
console.log(customArray instanceof MyArray); // true
console.log(customArray instanceof Array); // trueCode language: JavaScript (javascript)
```

These array properties are helpful for understanding and manipulating arrays in JavaScript, providing developers with valuable insights into the structure and characteristics of arrays. Understanding and using these properties can make working with arrays more efficient and powerful in your JavaScript code.

## Array Methods :

## Adding and Removing Elements

### push() and pop()

The `push()` method allows you to add one or more elements to the end of an array. It returns the new length of the array.

```javascript
fruits.push("orange");
// fruits is now ["apple", "banana", "cherry", "orange"]Code language: JavaScript (javascript)
```

Conversely, the `pop()` method removes the last element from an array and returns that element.

```javascript
let removedFruit = fruits.pop();
// removedFruit is "orange", fruits is ["apple", "banana", "cherry"]Code language: JavaScript (javascript)
```

### shift() and unshift()

`shift()` removes the first element from an array and returns it, shifting the remaining elements to lower indices.

```javascript
let removedFruit = fruits.shift();
// removedFruit is "apple", fruits is ["banana", "cherry"]Code language: JavaScript (javascript)
```

On the other hand, `unshift()` adds one or more elements to the beginning of an array and returns the new length.

```javascript
fruits.unshift("kiwi", "grape");
// fruits is now ["kiwi", "grape", "banana", "cherry"]Code language: JavaScript (javascript)
```

## Combining and Extracting Arrays

### concat()

The `concat()` method combines two or more arrays and returns a new array, leaving the original arrays unchanged.

```javascript
let colors1 = ["red", "green"];
let colors2 = ["blue", "yellow"];
let combinedColors = colors1.concat(colors2);
// combinedColors is ["red", "green", "blue", "yellow"]Code language: JavaScript (javascript)
```

### slice()

`slice()` extracts a portion of an array and returns a new array with the selected elements. It takes two arguments, the start index (inclusive) and the end index (exclusive).

```javascript
let animals = ["lion", "tiger", "cheetah", "leopard"];
let bigCats = animals.slice(1, 3);
// bigCats is ["tiger", "cheetah"]Code language: JavaScript (javascript)
```

## Iterating through Arrays

### forEach()

The `forEach()` method executes a provided function once for each array element. It is useful for performing actions on each element without the need for a traditional `for` loop.

```javascript
let numbers = [1, 2, 3];
numbers.forEach(function (number) {
    console.log(number);
});
// Output: 1, 2, 3Code language: JavaScript (javascript)
```

## Transforming Arrays

### map()

`map()` creates a new array by applying a provided function to each element of the original array. It is particularly useful when you want to transform the elements of an array and create a new array of the same length.

```javascript
let numbers = [1, 2, 3];
let squaredNumbers = numbers.map(function (number) {
    return number * number;
});
// squaredNumbers is [1, 4, 9]Code language: JavaScript (javascript)
```

### filter()

The `filter()` method creates a new array with all elements that pass a given test (provided by a function). It’s an excellent choice when you want to extract specific elements from an array.

```javascript
let ages = [25, 18, 30, 15, 22];
let adults = ages.filter(function (age) {
    return age >= 18;
});
// adults is [25, 18, 30, 22]Code language: JavaScript (javascript)
```

## Searching and Finding Elements

### find()

`find()` returns the first element in an array that satisfies a provided testing function. It’s handy when you need to find a single element based on a condition.

```javascript
let fruits = ["apple", "banana", "cherry"];
let result = fruits.find(function (fruit) {
    return fruit.length > 5;
});
// result is "banana"Code language: JavaScript (javascript)
```

### findIndex()

Similar to `find()`, but `findIndex()` returns the index of the first element that satisfies a provided testing function.

```javascript
let fruits = ["apple", "banana", "cherry"];
let index = fruits.findIndex(function (fruit) {
    return fruit.length > 5;
});
// index is 1 (index of "banana")Code language: JavaScript (javascript)
```

## Array Data Validation

### some() and every()

`some()` checks if at least one element in an array satisfies a provided testing function. It returns `true` if at least one element passes the test; otherwise, it returns `false`.

```javascript
let numbers = [1, 2, 3, 4, 5];
let hasEvenNumber = numbers.some(function (number) {
    return number % 2 === 0;
});
// hasEvenNumber is trueCode language: JavaScript (javascript)
```

`every()` checks if all elements in an array satisfy a provided testing function. It returns `true` if all elements pass the test; otherwise, it returns `false`.

```javascript
let numbers = [1, 2, 3, 4, 5];
let allEvenNumbers = numbers.every(function (number) {
    return number % 2 === 0;
});
// allEvenNumbers is falseCode language: JavaScript (javascript)
```

## Reducing Arrays

### reduce() and reduceRight()

The `reduce()` method applies a function to an accumulator and each element in the array (from left to right) to reduce it to a single value.

```javascript
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce(function (accumulator, current) {
    return accumulator + current;
}, 0);
// sum is 15Code language: JavaScript (javascript)
```

`reduceRight()` is similar to `reduce()`, but it processes the array from right to left.

## Sorting and Reversing

### sort()

The `sort()` method sorts the elements of an array in place and returns the sorted array. By default, it sorts elements as strings based on their Unicode code points.

```javascript
let fruits = ["banana", "cherry", "apple"];
fruits.sort();
// fruits is now ["apple", "banana", "cherry"]Code language: JavaScript (javascript)
```

To sort numeric values correctly, you can provide a compare function:

```javascript
let

 numbers = [3, 1, 2, 10];
numbers.sort(function (a, b) {
    return a - b;
});
// numbers is now [1, 2, 3, 10]Code language: JavaScript (javascript)
```

### reverse()

The `reverse()` method reverses the order of elements in an array in place.

```javascript
let colors = ["red", "green", "blue"];
colors.reverse();
// colors is now ["blue", "green", "red"]Code language: JavaScript (javascript)
```

## Checking for Element Existence

### includes() , indexOf() , and lastIndexOf()

`includes()` checks if an array includes a certain element and returns `true` or `false`.

```javascript
let fruits = ["apple", "banana", "cherry"];
let hasBanana = fruits.includes("banana");
// hasBanana is trueCode language: JavaScript (javascript)
```

`indexOf()` returns the first index at which a specified element can be found in the array or -1 if it’s not present.

```javascript
let fruits = ["apple", "banana", "cherry"];
let index = fruits.indexOf("cherry");
// index is 2Code language: JavaScript (javascript)
```

`lastIndexOf()` returns the last index at which a specified element can be found in the array or -1 if it’s not present.

```javascript
let fruits = ["apple", "banana", "cherry", "apple"];
let lastIndex = fruits.lastIndexOf("apple");
// lastIndex is 3Code language: JavaScript (javascript)
```

## Conclusion

JavaScript array methods are powerful tools for working with arrays. They simplify common tasks, provide efficient ways to process and transform data, and make your code more expressive and readable. By mastering these array methods, you’ll become a more proficient JavaScript developer, capable of handling complex data manipulation tasks with ease.

### Related posts:

[Array Data Structure](https://blog.khanwaseem.com/array-data-structure/)
[JavaScript – Operators](https://blog.khanwaseem.com/javascript-operators/)
[JavaScript -Strings](https://blog.khanwaseem.com/javascript-strings/)
[JavaScript-Form properties and methods](https://blog.khanwaseem.com/javascript-form-properties-and-methods/)

Powered by [YARPP](https://yarpp.com).
