JavaScript - Access Elements in JS Array
These are the following ways to Access Elements in an Array:
1. Using Square Bracket Notation
We can access elements in an array by using their index, where the index starts from 0 for the first element. We can access using the bracket notation.
const a = [10, 20, 30, 40, 50];
const v = a[3];
console.log(v);
2. Using forEach Loop
In this approach, we will use a loop for accessing the element. We can use for, forEach, or for...of methods for looping. The forEach()
method allows you to iterate over all elements in the array and perform an operation on each element.
const a = [100, 200, 300, 400, 500];
a.forEach((e, i) => {
console.log(e);
});
Output
100 200 300 400 500
3. Using map() Method
The Javascript map() method in JavaScript creates an array by calling a specific function on each element present in the parent array.
const a = [10, 20, 30, 40, 50];
const r = a.map((e, i) => {
console.log(e);
});
Output
10 20 30 40 50
4. Using find() Method
The find()
method returns the first element in the array that satisfies a provided testing function.
const a = [10, 20, 30, 40, 50];
const r = a.find((e) => e > 30);
console.log(r);
Output
40
5. Using Destructuring Assignment
Destructuring Assignment is a JavaScript expression that allows us to unpack values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, and nested objects and assigned to variables.
let [FN, , TN] = ["alpha", "beta", "gamma", "delta"];
console.log(FN);
console.log(TN);
Output
alpha gamma
6. Using filter() Method
The filter() method in JavaScript creates a new array containing elements that pass a specified condition. It iterates through each element of the array, executing the condition for each element and including elements that return true in the filtered array.
const a = [1, 2, 3, 4, 5];
const res = a.filter(e => e > 2);
console.log(res);
Output
[ 3, 4, 5 ]