What is indexOf() in JavaScript?

What is indexOf() in JavaScript?

·

2 min read


After a long time, a new post on JavaScript methods is here... Let's learn about the indexOf() method.


indexOf()

It accepts two parameters: The required parameter of searchValue indicates the content you want to search for in a string.

The optional start parameter indicates the position of the string in which the search will begin. If not specified, the search will start at the beginning. indexOf is case sensitive but can be sued with regex case-insensitive modifier.

**TLDR: Returns the position of starting point of work or -1 if not found.


const movieQuote = "I'm in a glass case of emotion!"

console.log(movieQuote.indexOf("emotion", 20)); 

//output
23

console.log(movieQuote[23]); 
//output
e

Use Case

indexOf can creatively be used for many things, including validation. This is used for dynamic content by finding a word and displaying that content as output or in the example below, push the item into a new array if not already existent.

const updateVegetablesCollection = (veggies, veggie) => {
    if (veggies.indexOf(veggie) === -1) {
        veggies.push(veggie); 
        console.log(`New veggies collection is: ${veggies}`); 
    } else if (veggies.indexOf(veggie) > -1) {
        console.log(`${veggie} already exists in the veggies collection.`); 
    }
}

let veggies = ['potato', 'tomato', 'chillies', 'green-pepper']; 

updateVegetablesCollection(veggies, 'spinach'); 
//output
New veggies collection is : potato,tomato,chillies,green-pepper,spinach

updateVegetablesCollection(veggies, 'spinach'); 
//output
spinach already exists in the veggies collection.

🤩Thanks For Reading | Happy Learning🥂

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!