1.

What is the issue with the below code and how it can be fixed? const array = [1, 2, 15, 4, 30, 7, 45]; console.log(array.sort());

Answer»

The most obvious answer to think is the value of “i” will be 0. So, LET’s put i = 0 and see what happens.

let i = 0; console.log(i * i); //Gives 0 console.log(i + 1); //Gives 1 console.log(i - 1); //Gives -1 console.log(i / i); //Gives NaN

Everything is ok, but the LAST one produce NaN(Not a Number) because “0 divide by 0 will produce infinity”

So, we need a number which is like zero but gives 1 if we divide it by itself. Fortunately there is such a number in JAVASCRIPT. The number is the minimum value that is allowed in JavaScript and is represented by Number.MIN_VALUE

let i = Number.MIN_VALUE; console.log(i * i); //Gives 0 console.log(i + 1); //Gives 1 console.log(i - 1); //Gives -1 console.log(i / i); //Gives 1

Now, what is this MIN_VALUE and why it produces the above correct DESIRED result. If we console log it we can see it’s a very small number 5e-324.

console.log(Number.MIN_VALUE); //5e-324

Now, this number in most cases behaves like a zero(0). Like when we multiply it by itself(i * i), add it to 1(i + 1) or SUBSTRACT it from 1(i -1).
But when we divide this small number by itself it produces 1.



Discussion

No Comment Found