Array in JavaScript
Dikshya Subedi
2 min read
In JavaScript, an array is a data structure that can hold multiple values of any type. Arrays are defined using square brackets [ ] and can contain elements separated by commas. Here are some examples of working with arrays in JavaScript:
Creating an Array:
// Creating an empty array
const empty array = [];
// Creating an array with initial values
const numbers = [1, 2, 3, 4, 5];
const names = ["Alice", "Bob", "Charlie"];
const mixed = [1, "two", true, null];
Accessing Array Elements:
const fruits = ["apple", "banana", "grape", "orange"];
// Accessing individual elements
console.log(fruits[0]); // Output: "apple"
console.log(fruits[2]); // Output: "grape"
// Modifying elements
fruits[1] = "kiwi";
console.log(fruits[0]); // Output: ["apple", "kiwi", "grape", "orange"];
Array Methods:
const numbers = [1, 2, 3, 4, 5];
// Adding elements
numbers.push(6); // Adds 6 to the end of the array
// Removing elements
numbers.pop(); // Removes the last element (5)
// Finding the length
const length = numbers.length; // length is now 4
});
Looping through an Array:
// Using a for loop
const fruits = ["apple", "banana", "grape", "orange"];
for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); }
// Output: apple banana grape orange
// Using forEach
fruits.forEach(function(fruit) { console.log(fruit); });
// Output: apple banana grape orange
// Using .map() to double each element in the array
const numbers = [1,2,3,4,5];
const doubledNumbers = numbers.map(function(number) { return number * 2; });
console.log(doubledNumbers);
// Output: [2, 4, 6, 8, 10]
// Using .filter() to create a new array with even numbers
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = numbers.filter(function(number) {
return number % 2 === 0;
});
console.log("Original array:", numbers);
// Output: Original array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log("Even numbers:", evenNumbers);
// Output: Even numbers: [2, 4, 6, 8, 10]
0
Subscribe to my newsletter
Read articles from Dikshya Subedi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by