- Home
- /
- Arrays and Array Methods
JavaScript Tutorial
IINTRODUCTION
JAVASCRIPT VARIABLES
JAVASCRIPT BASICS
JAVASCRIPT OBJECTS
DOM & BOM
OOPs
- Home
- /
- Arrays and Array Methods
Arrays and Array Methods
In JavaScript, arrays are a powerful and flexible way to store collections of data. Whether you’re keeping a list of numbers, names, or mixed values, arrays help organize and manipulate that data efficiently.
An array is created by wrapping elements inside square brackets []
. These elements can be of any type—numbers, strings, booleans, or even other arrays.
let items = [42, "Learn", true, [1, 2]];
In this case, items
contains four elements: a number, a string, a boolean, and a nested array. You can access each item using its index (starting from 0).
Getting the Length
The .length
property tells you how many elements are inside an array:
let data = [5, 10, 15];
console.log(data.length); // Output: 3
Adding Items – push()
Want to add something to the end of your array? Use .push()
:
let tools = ["HTML", "CSS"];
tools.push("JavaScript");
console.log(tools); // ["HTML", "CSS", "JavaScript"]
Removing the Last Item – pop()
The .pop()
method removes the last element from the array:
tools.pop();
console.log(tools); // ["HTML", "CSS"]
Removing the First Item – shift()
If you want to remove the item at the beginning of the array, use .shift()
:
let queue = ["first", "second", "third"];
queue.shift();
console.log(queue); // ["second", "third"]
Adding to the Start – unshift()
To add something to the beginning of an array:
queue.unshift("zero");
console.log(queue); // ["zero", "second", "third"]
Slicing an Array – slice()
You can extract a portion of an array using .slice(start, end)
. It doesn’t change the original array.
let fruits = ["apple", "banana", "cherry", "date"];
let sliced = fruits.slice(1, 3);
console.log(sliced); // ["banana", "cherry"]
Modifying In Place – splice()
The .splice()
method can remove, replace, or insert items in your array. It modifies the original array directly.
Here’s an example that replaces an element and inserts two new ones:
let courses = ["HTML", "CSS", "JS"];
courses.splice(1, 1, "React", "Node");
console.log(courses); // ["HTML", "React", "Node", "JS"]
In this case:
1
is the index to start at1
is the number of items to remove"React", "Node"
are the new items added at that position
Wrap-up
JavaScript arrays make it easy to store and manage data. Here’s what you now know how to do:
Get array length with
.length
Add items with
.push()
and.unshift()
Remove items using
.pop()
and.shift()
Slice out parts with
.slice()
Modify in-place with
.splice()
Each of these tools helps you take control of how data behaves in your code.