JavaScript array: The ultimate guide you need to start with

What is a JavaScript array ?

An array in JavaScript is an Object. To be specific, a Javascript array is a standard built-in object created with the Array constructor. An array is a collection of elements ordered by an index. Javascript arrays have the following characteristics:

  • Ordered: Arrays are ordered collections of elements. Each element is assigned a numerical index, starting from 0, which determines its position within the array.

JavaScript array

  • Dynamic Size: Arrays in JavaScript can dynamically grow or shrink as elements are added or removed. You don't need to predefine their size.

  • Heterogeneous: JavaScript arrays can store elements of different data types within the same array. For example, an array can contain a mix of numbers, strings, objects, or even other arrays.

const myArray = [2, 'dinesh', true, new Date( 12/12/23 ), { msg: "hello" },[1,2,3] ];
console.log(myArray);
//[2, "dinesh", true, Wed Dec 31 1969 16:00:00 GMT-0800 (Pacific Standard Time), Object { msg: "hello" }, Array [1, 2, 3]]
  • Mutable: The elements of a JavaScript array can be modified, replaced, or removed after they are added. This mutability allows for easy manipulation of array data.

JavaScript array methods

in JavaScript, the Array methods can be broadly categorized into the following groups based on their functionality.

CategoryMethod ExamplesDescription
Manipulation Methodspush(), pop(), shift(), unshift(), splice(), sort(), reverse()Mutating methods modify the original array directly or create a new array with modified elements.
concat(), slice(), filter()Non-mutating methods that return a new array or another value based on the operations performed, leaving the original array intact.
Iteration MethodsforEach(), map(), reduce(), filter(), some(), every(), find()Methods for looping or iterating over array elements and performing operations on each element or finding specific elements that meet certain criteria.
entries(), keys(), values()Iterators that provide a way to iterate over array elements using the for...of loop or by explicitly invoking the iterator.
Searching and SortingindexOf(), lastIndexOf(), includes()Methods for searching for specific elements within an array.
sort()Method to sort the elements of an array.
Transformation Methodsmap(), reduce(), filter(), flatMap()Methods that transform the array by modifying or manipulating its elements.
Stack and Queue MethodsStack Methods: push(), pop()Methods that simulate stack-like behavior using arrays.
Queue Methods: push(), shift()Methods that simulate queue-like behavior using arrays.
Miscellaneous MethodsLength and Size Methods: length property, size() methodMethods to get information about the length or size of an array.
Type Checking Methods: Array.isArray(), instanceof ArrayMethods to check if a variable is an array.

How to create a JavaScript array

You can create JavaScript arrays in multiple ways:

  • Array Literal Syntax
const myArray = [1, 2, 3, 4, 5];
  • Array Constructor: You can create an array using the Array constructor by calling it with the new keyword.
const myArray = new Array(1, 2, 3, 4, 5);

Alternatively, you can pass a single argument specifying the length of the array.

const myArray = new Array(5); // Creates an array with length 5, but all elements are initially empty.
  • Array.from(): The Array.from() method creates a new array from an array-like or iterable object. It can also be used to create an array from a string or a set of numbers.
const myArray = Array.from("Hello"); // Creates an array ["H", "e", "l", "l", "o"]
  • Spread Operator: The spread operator (...) can be used to create a new array by expanding another array or iterable.
const originalArray = [1, 2, 3];
const newArray = [...originalArray];
  • Array.of(): The Array.of() method creates a new array with the given elements as its elements. It is useful when you want to create an array with a single element.
const myArray = Array.of(1, 2, 3, 4, 5); // Creates an array [1, 2, 3, 4, 5]

How to add elements to a JavaScript array

There are several methods to add elements to an array.

javaScript array add elements

  • push(): Adds one or more elements to the end of the array.
const myArray = [1, 2, 3];
myArray.push(4, 5); // Adds 4 and 5 to the end of the array
console.log(myArray); // Output: [1, 2, 3, 4, 5]
  • unshift(): Adds one or more elements to the beginning of the array.
const myArray = [1, 2, 3];
myArray.unshift(4, 5); // Adds 4 and 5 to the beginning of the array
console.log(myArray); // Output: [4, 5, 1, 2, 3]
  • splice(): Adds or removes elements from anywhere within the array. It can be used to insert elements at a specific index.
const myArray = [1, 2, 3];
myArray.splice(1, 0, 4, 5); // Inserts 4 and 5 at index 1 without removing any elements
console.log(myArray); // Output: [1, 4, 5, 2, 3]

How to modify elements of a JavaScript array

You can modify the value of an element in an array by accessing it through its index and assigning a new value.

const myArray = [1, 2, 3];
myArray[1] = 4; // Modifies the second element to 4
console.log(myArray); // Output: [1, 4, 3]

How to remove elements from an array

There are several methods to remove elements from an array.

JavaScript array remove elements

  • pop(): Removes the last element from the array and returns it.
const myArray = [1, 2, 3];
const removedElement = myArray.pop(); // Removes 3 from the array
console.log(myArray); // Output: [1, 2]
console.log(removedElement); // Output: 3
  • shift(): Removes the first element from the array and returns it.
const myArray = [1, 2, 3];
const removedElement = myArray.shift(); // Removes 1 from the array
console.log(myArray); // Output: [2, 3]
console.log(removedElement); // Output: 1
  • splice(): Removes elements from anywhere within the array. It can be used to remove elements at a specific index.
const myArray = [1, 2, 3];
myArray.splice(1, 1); // Removes 2 from the array
console.log(myArray); // Output: [1, 3]

The JavaScript array length property

The length property is a built-in property of JavaScript arrays that returns the number of elements in an array. It provides a convenient way to determine the size or length of an array dynamically.

const myArray = [1, 2, 3, 4, 5];
console.log(myArray.length); // Output: 5

Here are some key points about the length property:

  1. Counting Elements: The count starts from 1 and includes all elements in the array, including empty or undefined elements.

  2. Dynamic Behavior: The length property automatically adjusts as elements are added to or removed from the array. When you add elements to the array, the length property increases accordingly, and when you remove elements, the length property decreases.

  3. Truncating the Array: You can modify the length property to truncate an array. Assigning a smaller value to the length property removes elements from the end of the array.

const myArray = [1, 2, 3, 4, 5];
myArray.length = 3; // Truncates the array to [1, 2, 3]
  1. Non-enumerable: The length property of an array is non-enumerable, which means it won't appear in for...in loops or be included in methods like Object.keys(). This behavior ensures that the length property doesn't interfere with iterating over the array's elements.

Traversing an array

There are several ways to traverse, or iterate over, an array in JavaScript. Here are some common methods for traversing an array:

  1. For Loop: You can use a traditional for loop to iterate over each element of the array using the array's index.
const myArray = [1, 2, 3, 4, 5];

for (let i = 0; i < myArray.length; i++) {
      console.log(myArray[i]);
}
  1. For...of Loop: The for...of loop is a more concise way to iterate over an array, directly accessing the elements without using an index.
const myArray = [1, 2, 3, 4, 5];

for (const element of myArray) {
    console.log(element);
}
  1. forEach() Method: The forEach() method allows you to execute a callback function for each element in the array. It provides a simpler and more expressive way to iterate over arrays.
const myArray = [1, 2, 3, 4, 5];

myArray.forEach(element => {
  console.log(element);
});
  1. map() Method: The map() method creates a new array by applying a callback function to each element of the original array. It is useful when you want to transform each element and collect the results.
const myArray = [1, 2, 3, 4, 5];
const mappedArray = myArray.map(element => element * 2);
console.log(mappedArray);

JavaScript provides several other array methods that can be used for traversal, such as filter(), reduce(), some(), and every(). These methods can perform specific operations on array elements while iterating over them.

How to copy an array in JavaScript

To copy an array in JavaScript, you can use various methods depending on your requirements. Here are a few commonly used approaches.

  1. The Spread Operator: The spread operator (...) can be used to create a shallow copy of an array. It spreads the elements of the original array into a new array.
const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];
  1. The Array.from() method: The Array.from() method can create a shallow copy of an array by passing the original array as an argument.
const originalArray = [1, 2, 3];
const copiedArray = Array.from(originalArray);
  1. The slice() method: The slice() method can be used to extract a portion of an array, and when used without any arguments, it creates a shallow copy of the entire array.
const originalArray = [1, 2, 3];
const copiedArray = originalArray.slice();
  1. The Array constructor: You can create a new array by passing the original array as an argument to the Array constructor using the new keyword.
const originalArray = [1, 2, 3];
const copiedArray = new Array(...originalArray);

These methods create a new array that is a separate instance from the original array. It means that modifying the copied array will not affect the original array, and vice versa.

However, if the array contains objects or arrays, keep in mind that it creates a shallow copy, meaning the references to the objects or arrays inside the original array are still shared between the original and copied arrays.

If you need a deep copy (where nested objects or arrays are also copied), you'll need to use more advanced techniques like recursion or libraries specifically designed for deep cloning.

How to check if a variable is an array

You can use the following Array methods to check if a certain variable is an array or not.

  1. Array.isArray(): This is a static method of the Array object. It takes a value as an argument and returns true if the value is an array, and false otherwise.
const myArray = [1, 2, 3];
console.log(Array.isArray(myArray)); // Output: true
const myVariable = "Hello";
console.log(Array.isArray(myVariable)); // Output: false
  1. instanceof Array: You can use the instanceof operator to check if a variable is an instance of the Array object. It returns true if the variable is an array, and false otherwise.
const myArray = [1, 2, 3];
console.log(myArray instanceof Array); // Output: true
const myVariable = "Hello";
console.log(myVariable instanceof Array); // Output: false

Summary

  • JavaScript arrays are objects that provide a way to store and manipulate collections of elements.

  • Arrays can hold values of any data type, including numbers, strings, objects, and even other arrays.

  • Arrays are zero-indexed, meaning the first element is at index 0, the second element is at index 1, and so on.

  • Arrays have a dynamic length that can be modified by adding or removing elements.

  • The Array object in JavaScript comes with a variety of methods for manipulating, iterating, searching, sorting, and transforming arrays.

  • Array methods can be categorized into groups such as manipulation, iteration, searching and sorting, transformation, stack and queue, and miscellaneous methods.

  • Some methods directly modify the original array (mutating methods), while others return new arrays or values without modifying the original (non-mutating methods).

  • Understanding and utilizing these methods can help you efficiently work with arrays and perform various operations on their elements.