Swapna Kumar Panda
Swapna Kumar Panda

@swapnakpanda

12 Tweets Dec 07, 2022
In JavaScript,
0 == '0' ➜ true
and
0 == [ ] ➜ true
but
'0' == [ ] ➜ false
Do you know why?
»» Superfast Explanation
⬘ Abstract equality (==)
Operand Types Conversion
➤ object, string ➜ string
➤ object, number ➜ number
➤ string, number ➜ number
⬙ Conversion
➤ [ ] ➜ '' ➜ 0
➤ '0' ➜ 0
Now, let's explain all these in detail.
➊ A crash course on ==
⬘ == is called an abstract equality operator.
⬗ It accepts 2 operands. Checks values sans their types.
⬙ If both operands have different types,
➤ object & string
both are converted to string
➤ all other cases
both are converted to numbers
➋ A crash course on type conversion
⬘ There are 2 important methods that get executed during type conversion.
➤ valueOf()
called during number conversion
if it doesn't return a primitive value, toString() is called
➤ toString()
called during string conversion
➋.➀ string to number
⬘ Before conversion, all whitespace characters are trimmed.
⬙ Then,
➤ An empty string converts to 0
➤ A string containing a valid numeric literal, converts to that number
➤ All other strings convert to NaN
➋.➁ array to string
⬘ An empty array returns an empty string.
⬙ Otherwise, a comma-separated string is returned by converting each element to string type
➤ null and undefined are converted to an empty string
➤ for all other values, their toString() is called
➋.➂ array to number
⬘ An array's valueOf() returns the array object itself which is not a primitive. Hence, its toString() is called.
⬙ Conversion happens like this
➤ First, object to string
➤ Then, string to number
➌.➀ Explanation of 0 == '0'
⬘ It's a number-to-string comparison. Hence, both are converted to numeric types.
⬙ '0' is a string and contains a numeric literal 0. So, it's converted to a number 0.
0 == '0'

0 == 0

true
➌.➁ Explanation of 0 == [ ]
⬘ It's a number-to-object comparison. Hence, both are converted to numeric types.
⬙ [ ] is an array. So, it's first converted to a string and then to a number.
➤ [ ] ➜ ""
➤ "" ➜ 0
0 == [ ]

0 == 0

true
➌.➂ Explanation of '0' == [ ]
⬘ It's a string-to-object comparison. Hence, both are converted to string types.
⬙ [ ] is an empty array that converts to an empty string.
'0' == [ ]

'0' == ''

false
➀ ➁ ➂
0 == '0' 0 == [ ] '0' == [ ]
⇩ ⇩ ⇩
0 == 0 0 == '' '0' == ''
⇩ ⇩ ⇩
true 0 == 0 false

true
Hey 👋
I am a Tech Writer, Educator, and Mentor from India 🇮🇳, here sharing
✰ Tutorials
✰ Tricks
✰ Career Tips
✰ Cheat Sheets
✰ Interview Questions
✰ Project Ideas
on
➠ Web Development
➠ Data Structures and Algorithms
➠ Databases
Thanks for reading. 🙏

Loading suggestions...