DEV Community

Cover image for JavaScript == vs ===, Which one you should use?
Yash K
Yash K

Posted on

JavaScript == vs ===, Which one you should use?

This tutorial is only for beginners in JavaScript. If you have a little bit of experience with JavaScript then you might be familiar with this. Otherwise, bear with me I will help you to make this clear.

If you know any other programming language then it would probably sound confused with these two operators. As most of the other programming languages have only one == comparison operator. But JavaScript gives us great control over conditions by these two keywords. It would be clear as we go through an example.

Example:
== vs === example

Output:
output

I think the above example would be enough to clear this difference.

As you can see, I have defined two variables num1 and num2 but note that num1 is assigned with "1" (String) and num2 is assigned with 1 (Number).

Then, I have put log statements with those operators. And you can see in the output that == operator gives true and === operator gives false as output.

Let me explain why this output produced because, == operator always compares values of given operands. It will not check the types of the given operands. Whereas, === operator always compares values plus type of the given operands. Here in our example "1" and 1, both are equals in terms of values but they are of different types.

Which one should you use?

  • The answer can be varied from different perspectives. In my opinion, if you can you should use === operator. Because it will give you more control then == operator.

I hope you liked it and let me know your thought on this topic by commenting down below.

Follow me on twitter: https://twitter.com/ykhokhaneshiya

Top comments (4)

Collapse
 
wheatup profile image
Hao

Have to mention Object.is:

console.log(0 == '0');              // true
console.log(0 === '0');             // false
console.log(Object.is(0, '0'));     // false

console.log(NaN == NaN);            // false
console.log(NaN === NaN);           // false
console.log(Object.is(NaN, NaN));   // true

console.log(+0 == -0);              // true
console.log(+0 === -0);             // true
console.log(Object.is(+0, -0));     // false
Collapse
 
steveblue profile image
Stephen Belovarich

Whichever one my linter tells me to? 🤷‍♂️

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

Always === that's what I have done for years. Corrosion equality is a terrible bug causing feature in JavaScript. Because 'false' == true. That's great for more junior developers 🤪.

Collapse
 
jinglescode profile image
Jingles (Hong Jing)

Ahhh