Arrays in JavaScript
Arrays
52
Arrays are a fundamental data structure in JavaScript that allows you to store and manipulate a collection of elements of the same type. Each element in the array is identified by its index, which starts from zero.
To create an array, you can use the array literal notation which uses square brackets:
let arr = []; // empty array let nums = [1, 2, 3, 4, 5]; // array of numbers let names = ["Alice", "Bob", "Charlie"]; // array of strings
You can access the elements of an array using the square bracket notation:
console.log(nums[0]); // output: 1 console.log(names[2]); // output: "Charlie"
You can also change the value of an element by assigning a new value to its index:
nums[0] = 6; console.log(nums); // output: [6, 2, 3, 4, 5]
Arrays have several built-in methods that allow you to manipulate their contents:
nums.push(6); // add 6 to the end of the array console.log(nums); // output: [1, 2, 3, 4, 5, 6] nums.pop(); // remove the last element from the array console.log(nums); // output: [1, 2, 3, 4, 5] names.shift(); // remove the first element from the array console.log(names); // output: ["Bob", "Charlie"] names.unshift("Alice"); // add "Alice" to the beginning of the array console.log(names); // output: ["Alice", "Bob", "Charlie"]
You can also use loops to iterate over the elements of an array:
for(let i = 0; i < nums.length; i++) { console.log(nums[i]); } nums.forEach(function(num) { console.log(num); });
Arrays are an essential data type in JavaScript and are widely used in building applications ranging from simple web pages to complex web applications, games, and more.
March 25, 2023