MakeW3web

JavaScript Array Accessing

In JavaScript, you can access array elements using their index, which is a zero-based integer representing the position of the element within the array. To access an element, you need to use the array's name followed by the index enclosed in square brackets `[]`.

Here's an example:

const fruits = ["apple", "banana", "cherry", "orange", "grape"];

// Accessing elements by index
console.log(fruits[0]); // Output: "apple"
console.log(fruits[1]); // Output: "banana"
console.log(fruits[2]); // Output: "cherry"

To access the last element of an array, you can use the array's `length` property, which returns the number of elements in the array:

const lastElement = fruits[fruits.length - 1];
console.log(lastElement); // Output: "grape"

Keep in mind that if you try to access an element that doesn't exist, JavaScript will return `undefined`:

console.log(fruits[5]); // Output: undefined

You can also use the square bracket notation to modify the value of an array element:

fruits[1] = "blueberry";
console.log(fruits); // Output: ["apple", "blueberry", "cherry", "orange", "grape"]

In summary, you can access and modify array elements in JavaScript using their zero-based index and the square bracket notation. Be cautious when accessing elements outside the bounds of the array, as it may result in `undefined`.

Was this page helpful?