Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 30, 2020 02:28 am GMT

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

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.300000000000000044408921sum === 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.


Original Link: https://dev.to/buttercubz/weird-and-curious-things-in-javascript-4o7h

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To