Array Basics in JavaScript
Key Concepts
- Creating Arrays
- Accessing Array Elements
- Modifying Array Elements
Creating Arrays
An array in JavaScript is a special variable that can hold more than one value at a time. Arrays are created using square brackets []
and can contain any data types, including numbers, strings, and objects.
Example:
let fruits = ["Apple", "Banana", "Cherry"]; let numbers = [1, 2, 3, 4, 5]; let mixed = ["Hello", 10, true, { name: "John" }];
Accessing Array Elements
Array elements are accessed using their index, which starts at 0 for the first element. To access an element, use the array name followed by the index in square brackets.
Example:
let fruits = ["Apple", "Banana", "Cherry"]; let firstFruit = fruits[0]; // "Apple" let secondFruit = fruits[1]; // "Banana" let lastFruit = fruits[fruits.length - 1]; // "Cherry"
Modifying Array Elements
Array elements can be modified by assigning a new value to a specific index. This allows you to update the contents of the array dynamically.
Example:
let fruits = ["Apple", "Banana", "Cherry"]; fruits[1] = "Orange"; // Now the array is ["Apple", "Orange", "Cherry"] fruits[3] = "Mango"; // Adds a new element at index 3, array is now ["Apple", "Orange", "Cherry", "Mango"]
Conclusion
Understanding the basics of arrays is crucial for any JavaScript developer. By knowing how to create arrays, access their elements, and modify them, you can efficiently manage and manipulate collections of data in your programs.