Pravayest Pravayest
Pravayest Pravayest

Reputation: 55

Strict equality comparison

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.

Upvotes: 0

Views: 775

Answers (2)

Abhinav Galodha
Abhinav Galodha

Reputation: 9878

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.

You can try to find the type using typeof operator.

So, if you try typeof '-1' it would return "string" and
typeof 'email.indexOf('@') would return "number"

So, the correct way of doing is to remove the quote around the number -1 as shown below.

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

From MDN

Strict equality compares two values for equality. Neither value is implicitly converted to some other value before being compared. If the values have different types, the values are considered unequal. Otherwise, if the values have the same type and are not numbers, they're considered equal if they have the same value. Finally, if both values are numbers, they're considered equal if they're both not NaN and are the same value, or if one is +0 and one is -0.

Upvotes: 4

bren
bren

Reputation: 4334

The Identity / Strict Equality (===) Comparison Operator will not convert types. This is what separates it from regular equality. .indexOf() will return a number, which is (obviously) not the same as the string -1. Theoretically, you could cast one to the other, but the best approach would just be to include the number, like so:

if (email.length == 0 || email.indexOf('@') == -1) {
  ... Your Code Here...
}

Upvotes: 0

Related Questions