DEV Community is a community of 847,300 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Erick Sosa Garcia

Posted on

weird and curious things in javascript

javascript was the first programming language I learned, but javascript is not a very intuitive language.

in this post list some curiosities of javascript and I will try to explain them.

#1

which goes first the egg or the chicken according to javascript.

If we take an array with two strings, one an emoji from an egg and the other that from a chicken and use the order function, how is it ordered?

``````
["π₯", "π"].sort(); // ?

``````

``````
["π", "π₯"]

``````

why?

javascript uses utf-16 for character encoding, when comparing the two emojis it does so using its utf-16 number and the chicken emoji has a lower number than the egg emoji and the chicken is placed first. it is for this reason that the uppercase characters when passing the classification function remain at the beginning since they have a smaller number in the utf-16 encoding.

#2

What happens if you add 0.1 + 0.2 and then compare that sum with 0.3?

``````
0.1 + 0.2 === 0.3 // false

``````

This occurs because the calculations are done with base 2 and the calculations cannot be completely accurate.

what happens behind is that it makes the following comparison

``````
const sum = 0.1 + 0.2;

sum.toFixed(24); // 0.300000000000000044408921

sum === 0.3 // false

``````

for this reason the comparison returns false, this problem is not exclusive to javascript, other languages ββlike python and ruby ββhave this problem.

if you want to work with extreme precision with numbers in javascript, the latest versions of js can now be used bigInt

#3

What is the result of the following instruction?

``````
"b" + "a" + + "a" + "a"

``````

``````
"b" + "a" + + "a" + "a"    // baNaNa

``````

This is evaluated as

``````
("b") + ("a") + (+ "a") + ("a") // baNaNa π

``````

by type coercion if we add the plus symbol to a string it will try to make it a number and since the letter "a" is not a number this returns NaN or (Not a Number) the other letters being concatenated resulting in the word baNaNa.

#4

we all know that we can comment code in javascript in two ways.

``````
// single comment

/*
multi line comment
*/

``````

but did you know that it is possible to comment using html comments.

``````
<!---
const baf = "π²";
--->

``````

this is possible for javascript interoperability within html.

Discussion (3)

#2 goes well beyond js. Learn your floats people.

Facundo Soria • Edited on

I really like your post !!, a clever way of presenting some curious concepts of js
another example related to #2:

``````0.1 + (0.2 + 0.3) === (0.1 + 0.2) + 0.3 // false
``````

#1 and #2 are (mostly) language independent

#4 is problematic in some things. It may not work in code run by jest.