1

I am building a BODMAS calculator using JavaScript, and working on some code to iterate through all the terms of the equation to find certain mathematical operators and numbers.

var AddPresent = EquationTerms.search(5);
console.log(AddPresent);

If number five is present in the string EquationTerms, it logs the index/position of the number in the string to the console of my browser. If it is not present, it logs -1. While this does not interfere with my program, I am curious: Why does it log -1, and not undefined, or null? I have searched online, but haven't found an answer which explains the reason. I would be grateful for one which explains this.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Chamika Fonseka
  • 29
  • 1
  • 1
  • 7
  • .search returns index of the string or character in the string. IF it does not get anything it returns -1 – Shubham Dec 11 '15 at 06:19
  • related: [Why does IndexOf return -1?](http://stackoverflow.com/q/8585897/1048572), [Why do Scala's index methods return -1 instead of None if the element is not found?](http://stackoverflow.com/q/14096518/1048572), [Why String.indexOf do not use exception but return -1 when substring not found?](http://stackoverflow.com/q/859494/1048572) – Bergi Dec 11 '15 at 06:27

2 Answers2

4

This is a pretty common convention, carried over from languages where integers and null were not interchangeable.

A strongly-typed language like C does not let you return null from a function that is declared as returning an integer, so you need to return some integer that denotes "not found". Because there is no way for an element to exist at a negative index, -1 is the most obvious choice.

user229044
  • 232,980
  • 40
  • 330
  • 338
0

-1 means "no match found".

The reason it returns -1 instead of "false" is that a needle at the beginning of the string would be at position 0, which is equivalent to false in JS. So returning -1 ensures that you know there is not actually a match.

Mandeep Singh
  • 1,287
  • 14
  • 34