Skip to content Skip to sidebar Skip to footer

Funny Way to Get 0 in Javascript

The Best JavaScript Meme I've Ever Seen, Explained in detail

TLDR: Coerce yourself to use triple equals.

I unintentionally found this JavaScript meme on Reddit, and it'southward the best i I've e'er seen.

best-js-meme-to-date-2

You can verify this meme's accuracy by running each code snippet in Developer Tools. The consequence isn't surprising, but however kind of disappointing.

Of course this footling experiment lead me to wonder...

Why Does This Happen?

why-does-this-happen

With feel, I've learned to embrace JavaScript's smooth sides while bewaring its prickly pines. Nonetheless, this corner instance's details still nicked me.

It's simply as Kyle Simpson says...

"I don't think anyone always really knows JS, not completely anyway."

When these cases pop upwards, information technology'due south best to consult the source–the official ECMAScript specification that JavaScript is built from.

With the spec in mitt, let'due south securely understand what's going on hither.

Panel 1 - Introducing Coercion

panel-1-1

If you run 0 == "0" in your programmer console, why does it render true?

0 is a number, and "0" is a string, they should never be the same! Well-nigh programming languages respect that. 0 == "0" in Java, for instance, returns this:

                error: incomparable types: int and Cord                              

This makes perfect sense. If yous desire to compare an int and String in Java, you must first convert them to the same type.

Merely this is JavaScript, you lot!
this-is-javascript

When you compare two values via ==, one of the values may undergo coercion.

Coercion–Automatically irresolute a value from one type to another.

Automatically is the key give-and-take hither. Instead of y'all explicitly converting your types, JavaScript does information technology for you lot behind the scenes.

scumbag-javascript

This is user-friendly if you lot're purposely exploiting it, but potentially harmful if you lot're unaware of its implications.

Here's the official ECMAScript Language Specification on that. I'll paraphrase the relevant part:

If 10 is Number and y is Cord, render 10 == ToNumber(y)

Then for our example of 0 == "0":

Since 0 is Number and "0" is Cord, return 0 == ToNumber("0")

Our string "0" has been secretly converted to 0, and at present we have a friction match!

                0 == "0" // true // The 2nd 0 became a number! // so 0 equals 0 is true....                              

that-string-secretly-became-a-number

Weird right? Well get used to it, we're not even halfway washed.

Panel 2 - Arrays Get Coerced Too

panel-2

This nonsense isn't limited to primitives like strings, numbers, or booleans. Here'due south our adjacent comparing:

                0 == [] // truthful // What happened...?                              

Coercion again! I'll paraphrase the spec'southward relevant office:

If 10 is String or Number and y is Object, return x == ToPrimitive(y)

Three things here:

1. Aye, arrays are objects

arrays-are-objects

Sorry to pause it yous.

two. Empty array becomes empty string

Again co-ordinate to the spec, JS first looks for an object's toString method to coerce information technology.

In the case of arrays, toString joins all of its elements and returns them equally a string.

                [1, two, three].toString() // "1,two,3" ['hello', 'world'].toString() // "how-do-you-do,globe"                              

Since our array'southward empty, nosotros have nothing to join! Therefore...

                [].toString() // ""                              

empty-array-coerces-to-empty-string-1

The spec'due south ToPrimitive turns this empty array into an empty string. References are here and here for your convenience (or confusion).

3. Empty cord then becomes 0

empty-strings-become-0

Y'all tin't make this stuff upwards. Now that nosotros've coerced the assortment to "", we're back to the first algorithm...

If x is Number and y is String, return x == ToNumber(y)

So for 0 == ""

Since 0 is Number and "" is String, return 0 == ToNumber("")

ToNumber("") returns 0.

Therefore, 0 == 0 one time once more...

coercion-every-time-2

Panel three - Quick Recap

panel-3-1

This is true

                0 == "0" // true                              

Because coercion turns this into 0 == ToNumber("0").

This is true

                0 == [] // true                              

Because coercion runs twice:

  1. ToPrimitive([]) gives empty string
  2. Then ToNumber("") gives 0.

So then tell me...according to the in a higher place rules, what should this return?

                "0" == []                              

Console 4 - FALSE!

panel-4-1

FALSE! Correct.

This part makes sense if you understood the rules.

Here's our comparison:

                "0" == [] // false                              

Referencing the spec once again:

If x is String or Number and y is Object, render x == ToPrimitive(y)

That ways...

Since "0" is Cord and [] is Object, render ten == ToPrimitive([])

ToPrimitive([]) returns empty string. The comparing has now become

                "0" == ""                              

"0" and "" are both strings, then JavaScript says no more than coercion needed. This is why nosotros become simulated.

Conclusion

just-use-triple-equals

Utilise triple equals and sleep soundly at nighttime.

                0 === "0" // simulated 0 === [] // false "0" === [] // simulated                              

It avoids coercion entirely, then I guess it's more than efficient too!

But the performance increase is almost meaningless. The real win is the increased confidence you'll take in your lawmaking, making that extra keystroke totally worth it.

Desire Free Coaching?

If you'd like to schedule a complimentary fifteen-30 minute phone call to talk over Front-End evolution questions regarding lawmaking, interviews, career, or annihilation else follow me on Twitter and DM me.

Afterwards that if you bask our first meeting, we can discuss an ongoing coaching human relationship that'll help you reach your Front-End development goals!

Thanks for reading

For more content like this, check out https://yazeedb.com!

Until next time!



Acquire to code for costless. freeCodeCamp's open source curriculum has helped more xl,000 people get jobs equally developers. Get started

bradleyrusoody.blogspot.com

Source: https://www.freecodecamp.org/news/explaining-the-best-javascript-meme-i-have-ever-seen/

Postar um comentário for "Funny Way to Get 0 in Javascript"