JavaScript is a powerful and versatile language, but it comes with its own set of quirks and oddities. Understanding these can help you write better code and debug issues more effectively. Here are ten lesser-known JavaScript quirks, complete with detailed examples.
1. Type Coercion in Comparisons
JavaScript performs type coercion when comparing values with ==
but not with ===
.
console.log(1 == '1'); // true
console.log(1 === '1'); // false
2. Floating Point Precision
JavaScript uses floating-point arithmetic, which can lead to precision issues.
console.log(0.1 + 0.2); // 0.30000000000000004
3. The typeof
Operator
The typeof
operator can sometimes produce unexpected results.
console.log(typeof null); // "object"
console.log(typeof NaN); // "number"
4. Automatic Semicolon Insertion
JavaScript automatically inserts semicolons at the end of lines, which can lead to bugs.
// This will not work as expected
const a =
1
console.log(a); // 1
// Correct way
const b = 1;
console.log(b); // 1
5. Falsy Values
JavaScript has several values that are considered falsy.
console.log(false == 0); // true
console.log(false == ''); // true
console.log(false == null); // false
6. Function Scope and Hoisting
JavaScript hoists function declarations and variables to the top of their containing scope.
console.log(foo()); // "Hello"
function foo() {
return "Hello";
}
console.log(bar); // undefined
var bar = "World";
7. Array and Object Conversion
Arrays and objects behave differently when converted to strings.
console.log([1, 2, 3].toString()); // "1,2,3"
console.log({a: 1, b: 2}.toString()); // "[object Object]"
8. this
Context
The value of this
can change depending on how a function is called.
const obj = {
value: 42,
getValue: function() {
return this.value;
}
};
console.log(obj.getValue()); // 42
const getValue = obj.getValue;
console.log(getValue()); // undefined
9. Prototype Chain
JavaScript objects have a prototype chain that can affect property lookups.
const parent = { value: 42 };
const child = Object.create(parent);
console.log(child.value); // 42
child.value = 100;
console.log(child.value); // 100
console.log(parent.value); // 42
10. Destructuring with Defaults
Destructuring can have default values, which can be tricky with null
and undefined
.
const { a = 10 } = { a: undefined };
console.log(a); // 10
const { b = 10 } = { b: null };
console.log(b); // null
Conclusion
JavaScript’s quirks can be surprising, but understanding them can help you write more predictable and reliable code. These examples provide a glimpse into some of the lesser-known aspects of the language. Keep exploring and experimenting to master JavaScript!