10 Mind-Boggling JavaScript Code Snippets That Will Confuse Even Experts!
Unraveling JavaScript's Quirks: 10 Puzzling Code Snippets That Will Test Your Knowledge!
Table of contents
- 1. Truthy Math Operations
- Code:
- Explanation:
- 2. Array Sorting Gotcha
- Code:
- Explanation:
- 3. Unexpected typeof Results
- Code:
- Explanation:
- 4. The !! Trick
- Code:
- Explanation:
- 5. Weird Coercion
- Code:
- Explanation:
- 6. Object Key Confusion
- Code:
- Explanation:
- 7. Function Hoisting Surprise
- Code:
- Explanation:
- 8. Adding Objects?
- Code:
- Explanation:
- 9. Deleting a Property vs. Variable
- Code:
- Explanation:
- 10. Object Comparison Trap
- Code:
- Explanation:
- Wrapping Up 🎯
JavaScript is full of surprises! From tricky type coercions to unexpected object behaviors, even experienced developers can get caught off guard. In this blog, we’ll explore 10 mind-boggling JavaScript code snippets that will challenge your understanding and sharpen your problem-solving skills. Whether you're preparing for an interview or just love exploring JavaScript quirks, these examples will keep you on your toes.
Let’s dive in and decode the confusion! 🚀
1. Truthy Math Operations
Code:
console.log(true + true * 7); // Output: 8
Explanation:
Implicit type-coercion converts true
to 1
when it encounters an arithmetic operator.
true + true * 7 => 1 + 1 * 7 => 8
2. Array Sorting Gotcha
Code:
console.log([1, 5, 15].sort()); // Output: [1, 15, 5]
Explanation:
In the sort
method, numbers in the array are treated as strings and sorted lexicographically.
Lexicographically, "1"
comes first, "15"
comes next, and "5"
comes last.
If we want to sort numerically instead of lexicographically, we should use:
console.log([1, 5, 15].sort((a, b) => a - b)); // Output: [1, 5, 15]
3. Unexpected typeof
Results
Code:
console.log(typeof NaN); // Output: "number"
console.log(typeof null); // Output: "object"
Explanation:
The type of
NaN
is"number"
, even thoughNaN
stands for "Not a Number."In JavaScript,
null
is considered an object, even though it represents nothing.
4. The !!
Trick
Code:
console.log(!!"false"); // Output: true
console.log(!!""); // Output: false
console.log(!!0); // Output: false
console.log(!!1); // Output: true
Explanation:
The !!
operator converts the following expression to a boolean:
"false"
→true
(Non-empty strings aretrue
.)""
→false
(Empty strings arefalse
.)0
→false
1
→true
5. Weird Coercion
Code:
console.log([] == ![]); // Output: true
Explanation:
![]
converts the array tofalse
.When comparing an empty array (
[]
) with a boolean, JavaScript coerces both to numbers.This results in:
0 == 0 // true
6. Object Key Confusion
Code:
const obj = {
1: "one",
0: "zero",
true: "truth",
false: "false"
};
console.log(obj[1]); // Output: "one"
console.log(obj[true]); // Output: "truth"
Explanation:
Object keys are automatically converted to strings.
When querying obj[true]
, it looks for the key "true"
, not the true
Boolean value.
7. Function Hoisting Surprise
Code:
foo(); // Output: "FOO"
bar(); // Output: TypeError: bar is not a function
function foo() {
console.log("FOO");
}
const bar = () => {
console.log("BAR");
};
Explanation:
During the memory creation phase, JavaScript initializes function declarations (foo
) with their full function definitions, whereas variables (bar
) are initialized with undefined
.
Since bar
is a variable holding an arrow function, calling bar()
before its declaration results in a TypeError.
8. Adding Objects?
Code:
console.log({} + []); // Output: "[object Object]"
console.log([] + {}); // Output: "[object Object]"
Explanation:
[]
(an empty array) is converted to an empty string (""
).When adding an object to an empty string, the object gets coerced to
"[object Object]"
.
9. Deleting a Property vs. Variable
Code:
var a = 10;
delete a;
console.log(a); // Output: 10
const obj = { b: 20 };
delete obj.b;
console.log(obj.b); // Output: undefined
Explanation:
The
delete
operator works only with object properties, not variables.delete a;
does nothing, whereasdelete obj.b;
removes the property from the object.
10. Object Comparison Trap
Code:
const a = {};
const b = {};
console.log(a === b); // Output: false
console.log(a == b); // Output: false
Explanation:
In JavaScript, objects are compared by reference, not by value.
Even though a
and b
are identical empty objects, they refer to two different memory locations, so the comparison returns false
.
If we want to compare objects by value, we can use:
JSON.stringify(a) === JSON.stringify(b);
Wrapping Up 🎯
JavaScript is a language full of surprises, and these tricky code snippets are just the tip of the iceberg. Understanding these quirks not only helps you avoid common pitfalls but also sharpens your debugging skills—a must for every JavaScript developer!
Did any of these examples surprise you? 🤔 Or do you have your own favorite confusing JS snippet? Drop a comment below and let’s discuss! 💬
If you found this post helpful, don’t forget to share it with your fellow developers, and stay tuned for more JavaScript deep dives! 🚀