How to use the for() Loop In Javascript
The for loop facilitates the execution of a set of instructions repeatedly until some condition evaluates and becomes false.
Example: In this example, an array is declared by using for() loop iteration up to the element found. By using this, we can check whether the value present in the array or not.
// Define an array
const array1 = [13, 23, 33, 43, 53];
// Initialize a flag variable
let p = false;
// Iterate through the array and check each element
for (let i = 0; i < array1.length; i++) {
if (array1[i] === 53) {
p = true;
break;
}
}
// Check the flag variable and log a message
if (p) {
console.log("53 is present in the array.");
} else {
console.log("53 is not present in the array.");
}
Output:
53 is present in the array
Check if an element is present in an array using JavaScript
Checking if an element is present in an array using JavaScript involves iterating through the array and comparing each element with the target value. If a match is found, the element is considered present; otherwise, it’s absent.
There are different approaches to finding an element present in an array, which is described below:
Table of Content
- Using includes() method
- Using the indexOf() method
- Using the find() method
- Using the for() Loop
- Using the Array.some() method
- Using a filter() method