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!

要查看或添加评论,请登录

Thilak Ramanie的更多文章

  • The Leaky Bucket: Understanding and Fixing Memory Leaks in JavaScript

    The Leaky Bucket: Understanding and Fixing Memory Leaks in JavaScript

    Memory management is a critical aspect of JavaScript development, particularly for web applications that run in…

  • Chameleon and the Changing this in JavaScript

    Chameleon and the Changing this in JavaScript

    In JavaScript, the keyword this can be one of the trickiest concepts to grasp. Its behavior changes based on the…

  • useEffect in React: A Comprehensive Guide

    useEffect in React: A Comprehensive Guide

    Effectively managing side effects is essential in React programming for maintaining application robustness and…

  • TanStack Query

    TanStack Query

    Been using React Query (aka) TanStack Query for a while and I'm excited to share how TanStack Query (formerly React…

社区洞察

其他会员也浏览了