Arrays in JavaScript

Table of contents

No heading

No headings in the article.

Arrays are a way to store a list of data items under a single variable name, where each value inside the list can be accessed individually.

Syntax to create an array:

const array_name = [item1, item2, ...];
or
const array_name = new Array(item1, item2, ...);

Arrays are usually declared using const keyword, which ensures that the array cannot be reassigned but elements inside the array can be reassigned.

Array elements can be accessed by referring their index number (array indexes start with 0). To change a value just assign a new value to that specific index.

The real strength of JavaScript arrays are the built-in methods and properties:

array_name.length    // Returns the number of elements
array_name.toString()    // Converts an array to a string
array_name.pop()    // Removes last element from array
array_name.push()    // Add element at the end of array
array_name.shift()    // Removes first element of array
array_name.unshift()    // Add element to array at the beginning
array_name.concat()    // Create new array by merging multiple arrays
array_name.splice()    // Add items at specific positions
array_name.slice()    // Grab a chunk from an array into a new array

Sorting Arrays in JavaScript:

array_name.sort()    // Sorts array alphabetically
array_name.reverse()    // Reverses elements in an array

Array Iteration can be done in JavaScript using forEach() and map() methods.