In the realm of JavaScript, arrays are one of the most versatile and widely used data structures. They allow you to store and manage collections of data efficiently. However, simply creating an array is just the beginning. To truly harness the power of arrays, you need to understand how to access and manipulate their elements using indexing and the length property.
In this article, we’ll dive deep into these fundamental concepts, providing you with practical examples and a solid foundation for working with arrays like a pro.
Array Indexing: Accessing Elements
Arrays in JavaScript are zero-based, meaning that the first element in the array has an index of 0, the second element has an index of 1, and so on. To access a specific element within an array, you can use its index in square brackets []
following the array's name. Here's an example:
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits[0]); // Output: 'apple'
console.log(fruits[2]); // Output: 'orange'
In this case, we’re accessing the first element (fruits[0]
) and the third element (fruits[2]
) of the fruits
array.