Logo


Indexof javascript


This is an array method. Indexof method finds an index of a specific value in an array. If the array has multiple duplicate values then indexof method returns the index of the first value match. It returns '1' if the value matched otherwise it will return '-1'.


1) If the array contains unique values.

1let arr =[1,2,3,4,5]
2  let index = arr.indexOf(3);
3  console.log(index) // 2

In the above example, indexOf finds the index of value '3' and returns it.


2) If the array doesn't contain unique values.

1let arr = [1, 2, 3, 4, 3, 5];
2  let index = arr.indexOf(3);
3  console.log(index); //2

In the above example,'3' is repeated two times but indexOf finds the index of first '3' and which is two (2)

3) Use of indexOf in string

1let arr = 'Hello i am Hassan';
2  let index = arr.indexOf('am');
3  console.log(index); //8

Here we are searing keyword 'am' which starts from index 8



Related Articles :



About

Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.

Follow him on Twitter

Hassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.

Follow him on Twitter

Tags

Click to see all tutorials tagged with:

© Copyright 2023 Pak Annonymous | Back To Homepage | Privacy Policy
Share