DEV Community

Cover image for Do you find difficulty choosing between =, == & === ?
Prashant Patel
Prashant Patel

Posted on

Do you find difficulty choosing between =, == & === ?

Assigning Operator (=)

It assigns the value to the variable.

const firstName = 'Prashant';
const favNumber = 13;
Enter fullscreen mode Exit fullscreen mode

Loose Equality Operator (==)

This operator compares two values & return true if they are equivalent or false if they are not.

function equality(value) {
     if(value == 13) {
          return 'Equal';
     }
     return 'Not Equal';
}
Enter fullscreen mode Exit fullscreen mode

In addition, it also compares two different data types (numbers & strings).

It is called as Type Coercion.

1 == '1' /* This will return true with the Loose Equality Operator. */
Enter fullscreen mode Exit fullscreen mode

Strict Equality Operator (===)

Unlike the Equality Operator, it does not compare two different data types.

Otherwise, it works similarly to Loose Equality Operator.

1 === '1' /* This will return false in case of the Strict Equality Operator. */
Enter fullscreen mode Exit fullscreen mode

More Examples

var favBook = 'Sapiens'; /* Assigns the value to the variable */

const 13 == '13'; /* It will perform a type conversion and it will return true. */

const 13 ==='13' /* It will not perform type conversion. Hence, it will return false. */
Enter fullscreen mode Exit fullscreen mode

A tip by
[deleted user] image

[Deleted User]

Ideally, you should always use === and !==, and never use ==, and !=.
Or to make it easy to use what can you do is configure your linter to always use === and !== in code editor.
The loose equality has too many pitfalls that are covered by the strict one.

Hope you found it helpful. Please let me know.
Why not connect on Twitter?

Top comments (1)

Collapse
 
13prashant profile image
Prashant Patel

Thanks for sharing this great tip Luke. Adding this into article!