loading...

weird and curious things in javascript

buttercubz profile image Erick Sosa Garcia ・2 min read

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(); // ?

the answer is


["πŸ”", "πŸ₯š"]

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"

the answer is


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

Posted on Jun 30 by:

buttercubz profile

Erick Sosa Garcia

@buttercubz

Hello I'm Erick I study Javascript, typescript, python, go, Node js and focused in deno πŸ¦• Creator of Trex package manager https://deno.land/x/trex

Discussion

markdown guide
 

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

 

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.