Common JavaScript Surprises!
Thilak Ramanie
MSc Computing student @ DCU | Secure Software Engineering Major | Proficient in React.js, Angular, Node.js | Eagerly seeking full-time roles in Dublin, Ireland.
Ever stumbled upon strange behaviors in JavaScript that left you scratching your head? Here are some quirks that might surprise you:
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
console.log(3 == '3'); // true
console.log(3 === '3'); // false
Watch out for type coercion with the double equals (==)!
console.log(x); // undefined
var x = 5;
Declarations are hoisted, but initializations aren't.
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.
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!
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.
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!