✅ Logical Operators in JavaScript – Complete Guide with Real Examples

Image
πŸ“Œ Introduction Logical operators help you combine conditions, control flow, and make decisions in JavaScript. In this guide, you’ll learn how to use && , || , and ! effectively with examples and real-world use cases. πŸ” What Are Logical Operators? Logical operators return a boolean value ( true or false ) and are used to evaluate expressions, especially within conditions like if statements. Operator Name Example Description && Logical AND a && b Returns true if both conditions are true || Logical OR a || b Returns true if either condition is true ! Logical NOT !a Reverses the boolean value ✅ 1. Logical AND ( && ) const age = 25; const isCitizen = true; if (age > 18 && isCitizen) { console.log("You can vote!"); } Short-circuiting: If the first condition is false, the second one isn’t evaluated. ✅ 2. Logi...

🧠 How to Use indexOf() in JavaScript – Complete Guide with Examples

indexOf in JavaScript cover image

πŸ” What is 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.

πŸ§ͺ Syntax

For Strings:

string.indexOf(searchValue, startIndex)

For Arrays:

array.indexOf(searchElement, fromIndex)

πŸ“˜ How indexOf() Works in Strings

const text = "JavaScript is amazing";
console.log(text.indexOf("Script")); // Output: 4

✅ Case Sensitivity:

console.log(text.indexOf("script")); // Output: -1

Note: indexOf() is case-sensitive.

πŸ” Finding the First Occurrence

const sentence = "I love JavaScript because JavaScript is fun!";
console.log(sentence.indexOf("JavaScript")); // Output: 7

πŸ•΅️‍♂️ Find All Occurrences in a String


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);
}

🧾 Using 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

🎯 Use indexOf() to Check If an Element Exists


if (fruits.indexOf("banana") !== -1) {
  console.log("Banana is in the list!");
}

🧠 Difference Between indexOf() and includes()

Feature indexOf() includes()
Return Type Index (or -1) true / false
Use Case Find position Check existence

⚡ Performance Tip


// Faster and cleaner
arr.includes("item");

// More flexible if you need index
arr.indexOf("item") !== -1

πŸ“Œ Real-World Use Case


const input = "Learn JavaScript the fun way!";
const term = "JavaScript";

if (input.indexOf(term) !== -1) {
  console.log(`The term "${term}" exists in the sentence.`);
}

❓ Common Interview Question

Q: How can you check if a string contains a word without using regex?

A: Use .indexOf() and compare the result with -1.

🧩 Practice Challenge

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

✅ Summary

  • Works On: Strings and Arrays
  • Returns: Index or -1
  • Case-Sensitive: Yes
  • Alternative: includes() for true/false checks

πŸ”— Related Posts:

🧠 Frequently Asked Questions (FAQs)

❓ Can indexOf() find objects in an array?

No. It only works for primitive values.

❓ What happens if there are multiple matches?

It returns only the first index found.

❓ Does indexOf() modify the original array?

No. It is a non-mutating method.


Comments

Popular posts from this blog

πŸš€ “JavaScript Debounce Made Simple + Live Example!”

πŸ” Deep Dive into useMemo in React.js: Optimize Performance Like a Pro

How to Fix npx tailwindcss init Error: “Could Not Determine Executable to Run”