Discuss Scratch

NanoRook
Scratcher
1000+ posts

[Resolved] Difference between == and === in JavaScript?

I'm learning JavaScript now and I've been told by the book I'm following that there's a “slight technical difference” between == and ===. What exactly is the difference? From my super basic number/variable comparisons using == and === they both seem to work exactly the same.

Last edited by NanoRook (Jan. 5, 2022 21:32:15)

Maximouse
Scratcher
1000+ posts

[Resolved] Difference between == and === in JavaScript?

== tries to convert the values to the same type before comparing them, so
0 == "0"
converts the text “0” to a number and returns true because both numbers are equal. This sometimes behaves weirdly:
"0" == 0 // true
[] == 0 // true
"0" == [] // false

The === operator doesn't do this, so comparing values of different types using it returns false. When both values have the same type, there is no difference.

Last edited by Maximouse (Jan. 5, 2022 17:45:13)

Jeffalo
Scratcher
1000+ posts

[Resolved] Difference between == and === in JavaScript?

adding on, use === if you want “strict equality”, for example:



it's useful to know this difference when dealing with user input within critical parts in your code.

Last edited by Jeffalo (Jan. 5, 2022 18:33:55)

NanoRook
Scratcher
1000+ posts

[Resolved] Difference between == and === in JavaScript?

Maximouse wrote:

== tries to convert the values to the same type before comparing them, so
0 == "0"
converts the text “0” to a number and returns true because both numbers are equal. This sometimes behaves weirdly:
"0" == 0 // true
[] == 0 // true
"0" == [] // false

The === operator doesn't do this, so comparing values of different types using it returns false. When both values have the same type, there is no difference.

Jeffalo wrote:

adding on, use === if you want “strict equality”, for example:



it's useful to know this difference when dealing with user input within critical parts in your code.

Ah, alright. I guess that's way more than a “slight” technical difference. Will be super helpful for the future, thank you for the replies.

Powered by DjangoBB