Loading...


Go Back

Next page
Go Back Course Outline

JavaScript Full Course


Arrays in JavaScript

An array in JavaScript is a special variable that can store multiple values in a single container. Arrays can hold numbers, strings, objects, or even other arrays.

How to Create an Array:
const fruits = ["apple", "banana", "orange"];
const numbers = [1, 2, 3, 4, 5];
Accessing Array Elements:

Array items are accessed using their index (starting from 0).

console.log(fruits[0]); // Output: apple
console.log(fruits[2]); // Output: orange
Common Array Methods:
  • push() – Adds an item to the end
  • pop() – Removes the last item
  • shift() – Removes the first item
  • unshift() – Adds an item to the beginning
  • length – Returns the number of elements
  • includes() – Checks if an item exists
  • indexOf() – Returns the index of an item
  • forEach() – Runs a function on each element
Example:
const colors = ["red", "green", "blue"];
colors.push("yellow"); // Adds 'yellow'
console.log(colors.length); // Output: 4
Looping Through Arrays:
colors.forEach(function(color) {
  console.log(color);
});
Tip:

Arrays are useful for storing lists of items and looping through them efficiently. JavaScript also supports advanced methods like map(), filter(), and reduce() for powerful data manipulation.

1. Creating Arrays

Creating arrays using literals or the Array constructor.

                        let fruits = ["apple", "banana", "cherry"];
                        console.log(fruits);  // Output: ["apple", "banana", "cherry"]
                                
Output:
["apple", "banana", "cherry"]


2. Array Methods

Different array methods for manipulating arrays.

2.1 push()

                        let numbers = [1, 2, 3];
                        numbers.push(4);
                        console.log(numbers);  // Output: [1, 2, 3, 4]
                                
Output:
[1, 2, 3, 4]


3. Multidimensional Arrays

Creating and accessing elements in a 2D array.

                        let matrix = [
                          [1, 2, 3],
                          [4, 5, 6],
                          [7, 8, 9]
                        ];
                        
                        console.log(matrix[0]);  // Output: [1, 2, 3]
                        console.log(matrix[1][2]);  // Output: 6
                                
Output:
[1, 2, 3]
6
Go Back

Next page