Common JavaScript Surprises!

Common JavaScript Surprises!

Ever stumbled upon strange behaviors in JavaScript that left you scratching your head? Here are some quirks that might surprise you:

  • Floating Point Arithmetic:

console.log(0.1 + 0.2); // 0.30000000000000004        

Floating-point arithmetic can lead to unexpected results due to binary representation.

One of the Fixes: +((0.1+0.2).toFixed(2))
// used + operator, since toFixed returns a string        

  • Equality Check:

console.log(3 == '3');  // true
console.log(3 === '3'); // false        

Watch out for type coercion with the double equals (==)!

  • Hoisting:

console.log(x); // undefined
var x = 5;        

Declarations are hoisted, but initializations aren't.

  • Closures and Loops:

for (var i = 0; i < 5; i++) {
     setTimeout(function() {
       console.log(i);
     }, 1000);
   }
output:
i times 5 (5,5,5,5,5)
// changing var to let outputs 0 1 2 3 4        

Sometimes, Closures in loops can lead to unexpected results.

  • Truthy and Falsy Values:

console.log(true + true);   // 2
console.log(true + false);  // 1
console.log(true * false);  // 0
console.log(true + 'hello'); // "truehello"        

Implicit conversion can be tricky!

  • NaN (Not-a-Number):

console.log(typeof NaN);    // "number"
console.log(NaN === NaN);   // false
console.log(isNaN('abc'));  // true
console.log(isNaN('1'));    // false
console.log(isNaN(1));      // false        

NaN is not equal to itself, and isNaN might surprise you.

  • Global Object:

var x = 10;
console.log(window.x);  // 10 (in a browser environment)        

Variables declared globally become properties of the global object.


JavaScript is a versatile language, and being aware of these unexpected behaviors can enhance the quality of our code. Feel free to share your most intriguing JavaScript revelations!

To view or add a comment, sign in

More articles by Thilak Ramanie

Explore content categories