Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to use === to compare strings in Javascript or is == enough? [duplicate]

Tags:

javascript

Possible Duplicate:
JavaScript === vs == : Does it matter which “equal” operator I use?

I can understand why === is necessary when comparing numbers, booleans, empty strings, etc, due to unexpected type conversions e.g.

var foo = 1; 
var bar = true; 
// bar == foo => true
// bar === foo => false

But can == ever introduce a bug when comparing a variable to a non-empty string literal? Is it more efficient to use == over === in this case?

like image 879
AlexMA Avatar asked Aug 08 '12 13:08

AlexMA


People also ask

Should I use == or === in JavaScript?

= Vs == VS === in JavaScript = in JavaScript is used for assigning values to a variable. == in JavaScript is used for comparing two variables, but it ignores the datatype of variable. === is used for comparing two variables, but this operator also checks datatype and compares two values.

Why would you use === instead of ==?

== Operator: This operator is used to check the given values are equal or not. If yes, it returns true, otherwise it returns false. === Operator: This operator is used to check the given values and its data type are equal or not. If yes, then it returns true, otherwise it returns false.

Can you use == to compare strings in JavaScript?

Explanation of the example: In the above example, when str1 and str2 are compared after using the toUpperCase method, the expression JAVASCRIPT == JAVASCRIPT would return true as they are the same strings after both being in upper case. Here, the equality operator (==) is used to check if both the strings are the same.

Can === be used for string comparison?

Yes, === can compare two strings, giving true or false as a result. The other examples you saw were talking about comparing strings when sorting lists of them.


2 Answers

This has been asked here a lot so I'll just let a better poster then myself answer.

Take a look here: http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html

The 3 equal signs mean "equality without type coercion". Using the triple equals, the values must be equal in type as well.

0==false   // true
0===false  // false, because they are of a different type
1=="1"     // true, auto type coercion
1==="1"    // false, because they are of a different type

source Difference between == and === in JavaScript

like image 94
Eric Robinson Avatar answered Sep 29 '22 05:09

Eric Robinson


It is a good practice to always use the identity operators (!== and ===) and perform type coercion manually only when you need to (e.g. Boolean(someVar) or Number(someVar)).

A fun fiddle.

like image 20
jbabey Avatar answered Sep 29 '22 03:09

jbabey