Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
does indexOf() in JS search all the elements of an array to execute?
const arr = ['a','b','c']; 
for (let char of arr) {
  console.log(char);
}

I believe that time complexity of code above is O(n).

const arr = ['a','b','c']; 
for (let char of arr) {
  console.log(arr.indexOf(char);
}

However, does indexOf() search all the elements? If does so, I believe time complexity of code above may be O(n^2)

I want to know whether indexOf() searches all the components as for loop or not.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

For time complexity, you always consider the worst case (for the OP's circumstance, each character is in the list at no specifically designated position). To take OP example array, doing arr.indexOf('c') would involve looking at every position until the character c is found (which is the last position). Therefore, assuming worst case scenario, the execution would take O(n) time for .indexOf(). As per @Nick Parsons comment, there are ways to improve the time of the underlying search algorithm using strategies like a binary search (which is O(log n) time complexity), but that implies the data is in some semi-structured format for any concepts like binary search to improve the time complexity.

about 4 years ago · Juan Pablo Isaza Report

0

If the browser vendors follow the language specification, then the answer is NO. It should return once a match is found. Under certain circumstances, it will return even without checking any elements. See ECMA262.

However, complexity would be the same, O(n^2).

about 4 years ago · Juan Pablo Isaza Report

0

Yes, the indexOf() function has a complexity of O(n). If the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched.

So your program will have big o notation of O(n^2)

You can find more about this here at MDN

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!