Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In javascript, is it better to use two equal signs or three when comparing variables [duplicate]

Tags:

javascript

I have noticed quite a few people use three equals signs when comparing things in Javascript, but I was taught to only use two. Can anyone shed some light on why someone would use three or two, and why do they both work?

-Thanks :)

Another user has pointed out that the question has already been asked, sorry about that guys, going to look at the answers on that one.

like image 737
entropy Avatar asked May 19 '13 11:05

entropy


4 Answers

All the following evaluations will return true

With == JS will type-juggle.

1 == '1'
1 == 1
1 == true
0 != true
0 == false

With === JS will not type-juggle

1 !== '1'
1 === 1
1 !== true
0 !== false
like image 64
Jordan Doyle Avatar answered Nov 15 '22 01:11

Jordan Doyle


The identity === operator is identical to the equality == operator except no type conversion is done therefore the types must be the same to be considered equal.

The == operator will compare for equality after doing any necessary type conversions.

The === operator will not do the conversion, so if two values are not the same type === will simply return false.

For me I generally always use === or !==, so as not to leave anything to chance.

like image 26
GriffLab Avatar answered Nov 14 '22 23:11

GriffLab


It depends on the use case. Triple equals is to check for identicality; in other words, not only equivalent, but the same type. Here's a good reference

like image 25
anomaaly Avatar answered Nov 14 '22 23:11

anomaaly


Triple equal will check the type of the variable also while double equal will only check for the match. If you want yo check the type of the variable, you need to use triple equals. Else you just need you use double equals.

like image 20
Anand Avatar answered Nov 15 '22 01:11

Anand