This statement simply checks an “@” symbol in a textbox.
if (string1.indexOf("@")==-1){
alert("Please input a valid email address!")
document.example.email.focus()
This. if (string1.indexOf("@")==-1){ why do we use -1 instead of 0.
it baffles me, since 0 is been used almost everywhere as a ‘null’ or ’empty’ value.
In most programming languages, indexes are zero-based, meaning that the first position in an index (again in most programming languages, a string is an index of characters) will be 0 – hence 0 can’t be used to indicate nothing was found anywhere.
To help clarify:
A
stringis an index ofchars(characters, or single-symbol types). So,"hi@ho.com"is an index containing 9 positions:Because indexes in JavaScript are zero-based they always start with their first position being 0.
indexOfuses -1 to tell you that it couldn’t find the@anywhere because it can’t use 0 since 0 is actually the first position of the index.Even if
stringsweren’t indexes most languages would still use -1 to indicate it couldn’t find the character and 0 to indicate the first position for reasons of tradition and de facto standards.In the above example,
indexOf("@")would return 2, not 3. Again, because indexes are zero-based.