JavaScript Arrays
JavaScript Arrays are ordered collections used to store multiple values in a single variable. Each value in an array is called an element, and each element has a numeric index that starts from 0.
Arrays are useful when a program has to work with a list of related values, such as prime numbers, student names, product items, scores, form inputs, selected files, or records returned from an API.
In JavaScript, arrays are dynamic. You can add, remove, update, search, filter, sort, and loop through array elements without declaring a fixed array size in advance.
JavaScript array literal syntax
The syntax to initialize an Array in JavaScript is
var arrayName = [ element1, element2, .. elementN ]
where arrayName is the name given to the array and would be referenced by this name in the script.
During initialization, the elements are enclosed in opening and closing square brackets, where the elements are separated by comma character.
In modern JavaScript, const or let is usually preferred over var. Use const when the array variable itself should not be reassigned, even though the array elements can still be changed.
const numbers = [2, 3, 5, 7, 11];
const names = ["Alice", "Bharat", "Chandra"];
const mixedValues = [101, "JavaScript", true];
Access JavaScript array elements using zero-based index
To access an element of an array, you may use index [0:N-1] with arrayName as shown in the following.
arrayName[index]
The first element is available at index 0, the second element is available at index 1, and the last element is available at index arrayName.length - 1.
const fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[fruits.length - 1]);
Apple
Banana
Mango
JavaScript array length property
The length property returns the number of elements in an array. It is commonly used while looping through an array or while accessing the last element.
const cities = ["Delhi", "Mumbai", "Chennai", "Kolkata"];
console.log(cities.length);
console.log(cities[cities.length - 1]);
4
Kolkata
JavaScript arrays can grow or shrink as elements are added or removed. The length value changes automatically when the array changes.
Add, update, and remove JavaScript array elements
You can update an existing array element by assigning a new value to its index. You can add elements using methods such as push() and unshift(), and remove elements using methods such as pop(), shift(), and splice().
const tasks = ["Plan", "Code", "Test"];
tasks[1] = "Develop"; // update element at index 1
tasks.push("Deploy"); // add element at the end
tasks.unshift("Discuss"); // add element at the beginning
tasks.splice(2, 1); // remove 1 element from index 2
console.log(tasks);
[ 'Discuss', 'Develop', 'Test', 'Deploy' ]
Loop through JavaScript arrays
JavaScript arrays can be looped using a for loop, for...of, or array methods such as forEach(). Use a regular for loop when you need the index. Use for...of when you only need the values.
const colors = ["Red", "Green", "Blue"];
for (let i = 0; i < colors.length; i++) {
console.log(i, colors[i]);
}
for (const color of colors) {
console.log(color);
}
Common JavaScript array methods with practical use
JavaScript provides many built-in array methods. Some methods change the original array, while others return a new value or a new array.
| Method | Use | Changes original array? |
|---|---|---|
push() | Adds element at the end | Yes |
pop() | Removes last element | Yes |
shift() | Removes first element | Yes |
unshift() | Adds element at the beginning | Yes |
splice() | Adds, removes, or replaces elements | Yes |
slice() | Returns selected part of an array | No |
map() | Creates a new array by transforming each element | No |
filter() | Creates a new array with matching elements | No |
reduce() | Reduces array values to a single result | No |
sort() | Sorts array elements | Yes |
const prices = [120, 80, 200, 40];
const discountedPrices = prices.map(price => price - 10);
const affordablePrices = prices.filter(price => price <= 100);
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(discountedPrices);
console.log(affordablePrices);
console.log(total);
[ 110, 70, 190, 30 ]
[ 80, 40 ]
440
Sorting numbers and strings in JavaScript arrays
The sort() method sorts array elements as strings by default. This works for many string arrays, but numeric arrays need a compare function to avoid incorrect ordering.
const numbers = [10, 2, 30, 4];
numbers.sort((a, b) => a - b);
console.log(numbers);
[ 2, 4, 10, 30 ]
For descending numeric order, use (a, b) => b - a as the compare function.
JavaScript arrays can store objects and nested arrays
An array can store strings, numbers, booleans, objects, functions, and even other arrays. In real applications, arrays of objects are common when working with users, products, posts, orders, or API data.
const students = [
{ id: 1, name: "Anika", score: 82 },
{ id: 2, name: "Rahul", score: 91 },
{ id: 3, name: "Meera", score: 76 }
];
const highScorers = students.filter(student => student.score >= 80);
console.log(highScorers);
Nested arrays are useful for matrix-like data, rows and columns, grids, or grouped values.
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[1][2]);
6
Check whether a value is a JavaScript array
Since JavaScript arrays are objects, typeof returns "object" for arrays. To check whether a value is an array, use Array.isArray().
const languages = ["JavaScript", "Python", "Java"];
console.log(typeof languages);
console.log(Array.isArray(languages));
object
true
JavaScript array best practices for beginners
- Use descriptive plural names such as
students,prices, ortasks. - Use
constfor arrays unless the variable must be reassigned. - Remember that array indexes start from
0. - Use
Array.isArray()instead oftypeofto check arrays. - Use
map(),filter(), andreduce()when you need transformed, filtered, or summarized data. - Use a compare function when sorting numeric arrays.
- Avoid leaving empty slots in arrays unless you intentionally need sparse array behavior.
Arrays Tutorials
In the following tutorial, we cover different topics of Arrays covering CRUD operations, sorting, etc.
- JavaScript – Create Array
- JavaScript – Array Length
- JavaScript – Access Elements of Array using Index
- JavaScript – Loop over an Array
- JavaScript – Array forEach()
- JavaScript – Join Elements of Array
- JavaScript – Add Element to Starting of Array
- JavaScript – Add Element to End of Array
- JavaScript – Remove First Element of Array
- JavaScript – Remove Last Element of Array
- JavaScript – Remove Element at Specified Index
- JavaScript – Concatenate Arrays
- JavaScript – Sort a Numeric Array
- JavaScript – Sort a String Array
- JavaScript – Slice an Array
- JavaScript – Reverse an Array
- JavaScript – Find Index of Element in Array
- JavaScript – Filter Array
Arrays based on Datatype
JavaScript arrays editorial QA checklist
- Confirm that every JavaScript array example uses zero-based indexing correctly.
- Check that new code blocks use PrismJS-compatible classes such as
language-javascript,syntax, oroutput. - Verify that examples explain whether an array method mutates the original array or returns a new array.
- Ensure numeric sorting examples include a compare function.
- Keep beginner explanations clear before introducing methods such as
map(),filter(), andreduce().
JavaScript arrays FAQs
What is an array in JavaScript?
An array in JavaScript is an ordered collection of values stored in a single variable. Each value is called an element and can be accessed using a numeric index.
Does a JavaScript array index start from 0 or 1?
A JavaScript array index starts from 0. For an array with N elements, the first index is 0 and the last index is N - 1.
Can JavaScript arrays store different data types?
Yes. A JavaScript array can store values of different data types, such as numbers, strings, booleans, objects, and other arrays. However, for clearer code, it is usually better to keep related values of the same kind in one array.
How do you check if a value is an array in JavaScript?
Use Array.isArray(value) to check whether a value is an array. The typeof operator is not enough because it returns "object" for arrays.
What is the difference between slice() and splice() in JavaScript arrays?
slice() returns a selected part of an array without changing the original array. splice() can add, remove, or replace elements and changes the original array.
Summary of JavaScript arrays
In this JavaScript Tutorial, we have learnt about JavaScript Arrays, how they are initialized, how indexes work, how to access and update elements, how to use common array methods, and how arrays are used with different data types. Arrays are one of the most frequently used JavaScript data structures because they make it easier to work with ordered lists of values.
TutorialKart.com