JavaScript Arrays

A JavaScript Array stores an ordered collection of values in one variable. Array indexes start at 0, so the first item is at index 0 and the last item is normally at array.length - 1.

const languages = ["JavaScript", "PHP", "Python"];
console.log(languages[0]);       // JavaScript
console.log(languages.length);  // 3

Use arrays for lists such as names, scores, products, form values, coordinates, or rows of data. Arrays can hold values of any JavaScript type, including objects and other arrays.

JavaScript array with indexed elements

Creating a JavaScript Array Top ↑

The array literal syntax [] is the usual and clearest way to create an array.

const empty = [];
const scripts = ["PHP", "JavaScript", "Python"];
const mixed = [42, "text", true, { name: "Ravi" }];

The Array constructor also exists, but a single numeric argument has special behavior: new Array(3) creates an array with three empty slots, not an array containing the number 3. See creating JavaScript arrays for the full set of creation patterns.

Accessing and Updating Array Elements Top ↑

const colors = ["red", "green", "blue"];
console.log(colors[1]); // green

colors[1] = "yellow";
console.log(colors);    // ["red", "yellow", "blue"]

Reading an index that does not exist returns undefined. Assigning to an index beyond the current end can create empty slots between the old and new positions.

Array Indexes and the length Property Top ↑

The length property is one greater than the highest array index. For a normal dense array, that is also the number of elements.

const items = ["A", "B", "C", "D"];
console.log(items.length);             // 4
console.log(items[items.length - 1]);  // D

Sparse arrays are an important edge case: length can be larger than the number of actually populated elements. The array length tutorial explains reading, changing, truncating, and clearing arrays with length.

Common JavaScript Array Methods Top ↑

OperationMethod / propertyWhat it does
CreateArray creationCreate arrays and add initial values.
Display / iterateDisplay array elementsRead one item or loop through the collection.
SizelengthRead or change the array length.
Add at endpush()Mutates the array and returns the new length.
Remove from endpop()Mutates the array and returns the removed value.
Add at startunshift()Adds one or more values at index 0.
Remove from startshift()Removes and returns the first value.
Combineconcat()Returns a new combined array without changing the originals.
Join as textjoin()Returns a string using a chosen separator.
Convert to texttoString()Returns comma-separated text.
Object valuevalueOf()Returns the array object itself; it is not a display method.
SearchindexOf()Finds the first matching index.
Extractslice()Returns a selected portion as a new array.
Add/remove by positionsplice()Mutates the array at a selected index.
Reversereverse()Reverses the array in place.
Sortsort()Sorts in place; numeric sorting needs a compare function.
String to arrayString.split()Splits a string into an array using a separator.
ClearEmpty an arrayRemove all items while choosing whether references should be preserved.
Nested dataTwo-dimensional arraysUse arrays inside arrays for rows and columns.

Array application demos

Add User Values with push() Add and Remove Values with splice()

Mutating vs Non-Mutating Array Operations Top ↑

Some methods change the existing array. Others return a new value or a new array. This difference matters when the same array is referenced elsewhere.

const original = [1, 2];
const sameArray = original;
original.push(3);              // mutates original
console.log(sameArray);        // [1, 2, 3]

const combined = original.concat([4, 5]); // new array
console.log(original);         // [1, 2, 3]
console.log(combined);         // [1, 2, 3, 4, 5]

push(), pop(), shift(), unshift(), splice(), sort(), and reverse() mutate. Methods such as concat() and slice() return new arrays.

Looping Through an Array Top ↑

Use a classic for loop when you need the numeric index, or for...of when you mainly need each value.

const languages = ["JavaScript", "PHP", "Python"];

for (let i = 0; i < languages.length; i++) {
  console.log(i, languages[i]);
}

for (const language of languages) {
  console.log(language);
}

Avoid using for...in as the general-purpose array loop because it enumerates property names rather than being designed specifically for array values. See displaying array elements for more iteration and DOM-output patterns.

Checking Whether a Value Is an Array Top ↑

const values = [10, 20, 30];
console.log(Array.isArray(values)); // true
console.log(Array.isArray({0: 10, length: 1})); // false

Array.isArray() is the reliable built-in test when your code needs to distinguish arrays from ordinary objects.

Copying an Array Top ↑

Spread syntax and slice() can make a shallow copy. Nested objects or nested arrays are still shared references.

const source = [1, 2, 3];
const copy1 = [...source];
const copy2 = source.slice();

console.log(copy1 === source); // false

Nested and Two-Dimensional Arrays Top ↑

const matrix = [
  [1, 2, 3],
  [4, 5, 6]
];

console.log(matrix[1][2]); // 6

JavaScript does not have a special two-dimensional array type; it uses arrays containing other arrays. See the two-dimensional array tutorial for jagged arrays, nested loops, and common initialization mistakes.

Common JavaScript Array Mistakes Top ↑

  • Using index 1 for the first item instead of index 0.
  • Reading array[array.length] instead of array[array.length - 1].
  • Expecting push() or unshift() to return the array; they return the new length.
  • Expecting pop() or shift() to return the new array; they return the removed value.
  • Forgetting that many array methods mutate the original array.
  • Using new Array(5) when you intended an array containing the number 5.
  • Using for...in when for...of or an index loop better matches the task.
  • Assuming a shallow copy duplicates nested objects.

JavaScript Array Videos Top ↑

The following Plus2net videos demonstrate creating arrays and displaying array elements.

Display Array Elements




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer