This tutorial aims to introduce the basics of JavaScript arrays. You will learn how to create, access, and modify arrays, and understand their importance in JavaScript programming.
By the end of this tutorial, you will be able to:
- Define and create JavaScript arrays
- Access and modify array elements
- Understand and use basic array methods
Basic knowledge of JavaScript is required, including understanding of variables and data types.
An array is a special variable that can hold multiple values at a time. It is useful when you want to store multiple values under a single name.
In JavaScript, an array can be created in two ways:
1. Array Literal: This is the most common way to create an array.
let fruits = ["apple", "banana", "mango"];
new
keyword.let fruits = new Array("apple", "banana", "mango");
Array elements are accessed using their index number. Array indices start from 0, meaning the first element is at index 0, the second at index 1, and so on.
let firstFruit = fruits[0]; // Outputs: apple
You can modify an existing element in an array by accessing it directly and assigning a new value.
fruits[1] = "blueberry"; // Changes the second element (banana) to blueberry
JavaScript arrays have several methods that can be used to manipulate them. Some of the most common ones include:
- push()
: Adds a new element to the end of an array
- pop()
: Removes the last element from an array
- shift()
: Removes the first element from an array
- unshift()
: Adds a new element to the start of an array
- length
: A property that returns the number of elements in an array
let fruits = ["apple", "banana", "mango"]; // Create an array
console.log(fruits[0]); // Access the first element - Outputs: apple
fruits[1] = "blueberry"; // Modify the second element
console.log(fruits); // Outputs: ["apple", "blueberry", "mango"]
let fruits = ["apple", "banana", "mango"]; // Create an array
fruits.push("orange"); // Add a new element to the end
console.log(fruits); // Outputs: ["apple", "banana", "mango", "orange"]
let lastFruit = fruits.pop(); // Remove the last element
console.log(lastFruit); // Outputs: orange
console.log(fruits.length); // Outputs: 3
In this tutorial, we have covered the basics of JavaScript arrays. We learned how to create, access, and modify arrays, and we discussed some basic array methods.
To further your understanding of JavaScript arrays, explore more complex array methods like sort()
, splice()
, slice()
, and concat()
. You can also learn about multidimensional arrays.
let movies = ["Inception", "The Dark Knight", "Memento"];
movies.push("Dunkirk");
movies.shift();
console.log(movies); // Outputs: ["The Dark Knight", "Memento", "Dunkirk"]
function findMax(arr) {
return Math.max(...arr);
}
console.log(findMax([1, 2, 3, 4, 5])); // Outputs: 5
function transpose(matrix) {
return matrix[0].map((_, i) => matrix.map(row => row[i]));
}
console.log(transpose([[1,2,3],[4,5,6],[7,8,9]])); // Outputs: [[1,4,7],[2,5,8],[3,6,9]]