Open In App

JavaScript Program to Access Elements in an Array

In this article, we will learn how to access elements in an array using JavaScript. The Arrays in JavaScript are zero-indexed which means the first element is accessed using index 0 and the second element with index 1 and so on. Accessing elements in an array is a fundamental operation and is essential for various programming tasks.

Below are the following approaches through which we can access elements in an array using JavaScript:



Approach 1: Using square bracket notation

You 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.

Example: This example shows the use of the above-explained approach.






const array = [10, 20, 30, 40, 50];
const GFG = array[3];
console.log(GFG);

Output
40

Approach 2: Using loop(for or forEach or for…of) Method

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.

Example: This example shows the use of the above-explained approach.




const array = [100, 200, 300, 400, 500];
array.forEach((element, index) => {
  console.log(`The Element at index ${index}: ${element}`);
});

Output
The Element at index 0: 100
The Element at index 1: 200
The Element at index 2: 300
The Element at index 3: 400
The Element at index 4: 500

Approach 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.

Example: This example shows the use of the above-explained approach.




const array = [10, 20, 30, 40, 50];
const geek = array.map((element, index) => {
    return `The Element at index ${index}: ${element}`;
});
  
console.log(geek);

Output
[
  'The Element at index 0: 10',
  'The Element at index 1: 20',
  'The Element at index 2: 30',
  'The Element at index 3: 40',
  'The Element at index 4: 50'
]

Approach 4: Using find() Method

The find() method returns the first element in the array that satisfies a provided testing function.

Example: This example shows the use of the above-explained approach.




const array = [10, 20, 30, 40, 50];
const geek = array.find((element) => element > 30);
console.log(geek);

Output
40

Approach 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.

Example: This example shows the use of the above-explained approach.




let [firstName, , thirdName] = ["alpha", "beta", "gamma", "delta"];
  
console.log(firstName);//"alpha"
console.log(thirdName);//"gamma"

Output
alpha
gamma

Article Tags :