✅ Logical Operators in JavaScript – Complete Guide with Real Examples

indexOf()
in JavaScript?The indexOf()
method in JavaScript is used to find the position (index) of a specific element within a string or array. If the item is not found, it returns -1
.
string.indexOf(searchValue, startIndex)
array.indexOf(searchElement, fromIndex)
indexOf()
Works in Stringsconst text = "JavaScript is amazing";
console.log(text.indexOf("Script")); // Output: 4
console.log(text.indexOf("script")); // Output: -1
Note: indexOf()
is case-sensitive.
const sentence = "I love JavaScript because JavaScript is fun!";
console.log(sentence.indexOf("JavaScript")); // Output: 7
const str = "JS is cool. JS is powerful. JS is everywhere!";
let index = str.indexOf("JS");
while (index !== -1) {
console.log("Found at:", index);
index = str.indexOf("JS", index + 1);
}
indexOf()
with Arrays
const fruits = ["apple", "banana", "cherry", "apple"];
console.log(fruits.indexOf("apple")); // 0
console.log(fruits.indexOf("cherry")); // 2
const numbers = [1, 5, 10, 15];
console.log(numbers.indexOf(10)); // 2
console.log(numbers.indexOf(20)); // -1
indexOf()
to Check If an Element Exists
if (fruits.indexOf("banana") !== -1) {
console.log("Banana is in the list!");
}
indexOf()
and includes()
Feature | indexOf() |
includes() |
---|---|---|
Return Type | Index (or -1) | true / false |
Use Case | Find position | Check existence |
// Faster and cleaner
arr.includes("item");
// More flexible if you need index
arr.indexOf("item") !== -1
const input = "Learn JavaScript the fun way!";
const term = "JavaScript";
if (input.indexOf(term) !== -1) {
console.log(`The term "${term}" exists in the sentence.`);
}
Q: How can you check if a string contains a word without using regex?
A: Use .indexOf()
and compare the result with -1
.
Problem: Write a function that finds if the word "React" exists in a sentence and returns its position.
function findReact(sentence) {
return sentence.indexOf("React");
}
console.log(findReact("I love React and JavaScript")); // Output: 7
includes()
for true/false checksindexOf()
find objects in an array?No. It only works for primitive values.
It returns only the first index found.
indexOf()
modify the original array?No. It is a non-mutating method.
Comments
Post a Comment