Interesting things: How 1 is equal to 0 in JavaScript

Navigation

Introduction

Yes, we can make 1 equal to 0 in JavaScript.
We'll do exactly that today.

How it works

Obviously, we can't compare the numbers directly.
But we can use a very simple concept of JavaScript: The concept of truthy values. A value is truthy when it's not an empty string, 0, undefined, null or whatsoever.
We will do a small conversion that does exactly the same with both numbers: We are going to convert the numbers to strings.
Non-empty strings are truthy, but we still can't compare them directly as "0" is not "1". But, they are truthy.
Our next step is to convert the strings (or the truthiness of the strings) into a truth value. It isn't important what truth value, so I just used a "NOT". Both strings are truthy, so both NOTtings will give us a false.
And what happens if we compare false with false? We will get true!

Final script

You may run this script in your console (F12 in most browsers).

(!(0 + "") == !(1 + ""))

The console should put out a true.

And that's it!

Thanks for reading this article. I hope you learned something about truthy values and conversion in JavaScript with the help of this blog entry. See you in the next one!