![]() |
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: Table of Content Approach 1: Using square bracket notationYou 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.
Output 40 Approach 2: Using loop(for or forEach or for…of) MethodIn this approach, we will use a loop for accessing the element. We can use for, forEach, or for…of methods for looping. The Example: This example shows the use of the above-explained approach.
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() MethodThe 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.
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() MethodThe Example: This example shows the use of the above-explained approach.
Output 40 Approach 5: Using Destructuring AssignmentDestructuring 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.
Output alpha gamma Approach 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. Example: In this example we filters elements from the array that are greater than 2 using the filter method. The resulting filteredArray contains only these elements, and it is logged to the console.
Output [ 3, 4, 5 ] |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |