Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should you use === vs ==, !== vs !=, etc.. in javascript? [duplicate]

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

What are the differences between === vs == and !== vs !=?

When should you use each one?

like image 597
Matt Avatar asked Jul 07 '09 20:07

Matt


People also ask

Why do we prefer === and !== Over == and != In JavaScript?

The strict equality operator ( === ) behaves identically to the abstract equality operator ( == ) except no type conversion is done, and the types must be the same to be considered equal. The == operator will compare for equality after doing any necessary type conversions.

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

== check if the one side is equal to the second one, while the === check if the left side is equal to the second one but from the same type. check if both are the same string and both are string values. Note also there is the !== operator that it does negative value and type comparison.

Why === is used in JavaScript?

The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.

What is != and !== In JavaScript?

The strict inequality operator ( !== ) checks whether its two operands are not equal, returning a Boolean result. Unlike the inequality operator, the strict inequality operator always considers operands of different types to be different.


2 Answers

=== is the Identity operator, and is used to test that value and type are equal.

so..

"3" == 3 // true "3" === 3 // false 1 == true // true 1 === true // false "1" == true // true "1" === true // false 

so when you care that value and type are equal, or not equal use Identity operators === or !==

like image 171
Matthew Vines Avatar answered Sep 23 '22 22:09

Matthew Vines


The "normal" == operators in javascript perform type coercion, and try their best to do things like treat a string as number or an object as a string where required. The longer === operators will not do type coercion, but rather a strict comparison within the type.

like image 35
Joel Coehoorn Avatar answered Sep 22 '22 22:09

Joel Coehoorn