Home:ALL Converter>Strict equality comparison

Strict equality comparison

Ask Time:2017-01-26T23:21:16         Author:Pravayest Pravayest

Json Formatter

I have contact form. And I use js for form field validation:

if(email.length == 0 || email.indexOf('@') == '-1'){
    var error = true;
}

but I want to use strict equality comparison for better performance. So I try

if(email.length === 0 || email.indexOf('@') === '-1'){
        var error = true;
    }

but it isn't work.

Author:Pravayest Pravayest,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/41876812/strict-equality-comparison
Abhinav Galodha :

For Strict Equality, The value should be equal as well as the type should be the same. As per your code the '-1' is of type string but indexOf returns an number. The === operator doesn't do the conversion, so even if the values are equal but are not of the same type === will simply return false.\n\nYou can try to find the type using typeof operator.\n\nSo, if you try typeof '-1' it would return \"string\" and\n typeof 'email.indexOf('@') would return \"number\"\n\nSo, the correct way of doing is to remove the quote around the number -1 as shown below.\n\nif(email.length === 0 || email.indexOf('@') === -1){\n var error = true;\n }\n\n\nFrom MDN \n\n\n Strict equality compares two values for equality. Neither value is\n implicitly converted to some other value before being compared. If the\n values have different types, the values are considered unequal.\n Otherwise, if the values have the same type and are not numbers,\n they're considered equal if they have the same value. Finally, if both\n values are numbers, they're considered equal if they're both not NaN\n and are the same value, or if one is +0 and one is -0.\n",
2017-01-26T15:23:16
yy