Swapna Kumar Panda
Swapna Kumar Panda

@swapnakpanda

14 تغريدة Dec 07, 2022
How in JavaScript,
[ ] == [ ] ➔ false
and,
[ ] == ![ ] ➔ true
➊ What is [ ] and what does it do?
⬘ [ ] is an array literal.
⬗ [ ] creates an empty array object.
⬙ Each time we use [ ], a new array object is created.
⬖ Hence, each [ ] references different objects in memory.
➋ Operator Precedence of "!" and "=="
⬘ ! is
❯ a logical NOT operator
❯ a unary operator
single operand
⬙ == is
❯ an abstract equality operator
❯ a binary operator
2 operands
✧ ! has higher precedence and will be executed first.
➌ How does "!" operate?
⬘ ! accepts any type of data as input.
⬗ It converts the input to a boolean value.
⬙ It returns the opposite boolean value.
➍ How does "==" operate?
The behavior of == is complex. For simplicity, we will discuss some relevant things in this thread.
➤ object to object
➤ object to boolean
➍.➀ "object to object" comparison
== returns true only if both operands reference the same object.
⚠️ Just keep in mind that, in our case, [ ] always creates a new object. Hence, all [ ]s reference the different objects.
➍.➁ "object to boolean" comparison
== converts both the operands to ❝numbers❞ before comparing.
⬘ Boolean "false" is converted to 0.
⬙ Boolean "true" is converted to 1.
⬗ Array literal [ ] is converted to 0.
➎ What all converts to "false"?
Only 7 things in JavaScript.
➤ false
➤ 0 (both +0 and, -0)
➤ 0n (bigint Zero)
➤ null
➤ undefined
➤ NaN
➤ "" (empty string)
⚠️ All objects, including an empty array ([ ]), are always converted to "true".
➏ How is [ ] converted to boolean and number?
⬘ [ ] is an object. Hence, its boolean conversion will return "true".
⬙ [ ] converts to "0" for number conversion.
⇥ [ ] ➔ true
⇥ [ ] ➔ 0
🏁 Finally, let's execute
➀ [ ] == [ ]
⬘ Here, both operands are objects
⬗ For object-to-object comparison, == checks if both operands have reference to the same object
⬙ [ ] creates a new object each time and, hence has a different reference
✔ So, it returns "false"
➁ [ ] == ![ ]
⬘ ! has higher precedence and will be executed first.
⬙ ! converts the operand to boolean and returns the opposite boolean value.
![ ] ➔ !true ➔ false
❑ The expression becomes [ ] == false
⬘ It's now an object-to-boolean comparison.
⬙ For an object-to-boolean comparison, == converts both operands to numbers before comparing.
⇥ [ ] ➔ 0
⇥ false ➔ 0
❒ The expression becomes 0 == 0
✔ It returns "true"
➁ ➀
[ ] == ![ ] [ ] == [ ]
⇩ ⇩
[ ] == !true false

[ ] == false

0 == 0

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. 🙏

جاري تحميل الاقتراحات...