JavaScript Gotchas

Javascript is usually considered a wild wild west language. There are countless memes made about how Javascript is the weird and quirky language that no one wants to touch. You can see many blog posts about it here and here.

In this post, I would like to explore some of the common gotchas of the Javascript language.


Math.min() > Math.max()

Math.min() is greater than Math.max(). This sounds weird, right? If no arguments are given, Math.min() returns infinity and Math.max() returns -infinity. Why does Math.min() return Infinity? Well Math.min(arg1, arg2,..) will return the smallest number in the list.

If there is only one argument provided, then it will return that number. So if the default argument is -Inifinity, then for every number provided in the argument list, it will always return -Infinity, which renders the function useless. Therefore Inifinity is the default value, and thus if any one single argument is provided, then that number would be the result returned.

Math.min(1) 
// 1
Math.min(1, infinity)
// 1
Math.min(1, -infinity)
// -infinity


0.1 + 0.2 !== 0.3

Why does 0.1 + 0.2 !== 0.3 in Javascript? If you brought up your console and typed in that equation, you would see the following:

0.1 + 0.2
// 0.30000000000000004

This is actually not a Javascript specific issue, instead a general issue with computing.

Floating number can’t store properly all decimal numbers because they store stuff in binary. Internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.

When the code is compiled or interpreted, your 0.1 is already rounded to the nearest number in that format, which results in a small rounding error even before the calculation happens.

So how to avoid this issuse? Instead of doing operations with the floating numbers, convert them to integers first, do the operation second, and display the result with decimal last.


Difference of a Function Expression from a Function Declaration

In usage, the key difference is that function declarations are hoisted, while function expressions are not. That means function declarations are moved to the top of their scope by the JavaScript interpreter, and so you can define a function declaration and call it anywhere in your code. By contrast, you can only call a function expression in linear sequence: you have to define it before you call it.

// Function Declaration. Auto hoisted, can call anywhere
function sum(x, y) {
  return x + y;
};

// Function Expression: ES5. You cannot call this anywhere*
var sum = function(x, y) {
  return x + y;
};

There are a lot more weird and quirky behaviors in Javascript. Look out my next post in the Javascript Gotchas series!