JavaScript is full of tiny yet powerful tricks that can make your code cleaner, faster, and more readable. Some of these feel like straight-up magic when you first discover them! 🧙♂️
Here are a few mind-blowing JavaScript tricks that you can start using today.
1. Short-Circuit Evaluation (Replace If-Else)
Tired of writing boring if statements? You can simplify them using logical operators like && and ||.
// Instead of this:
if (user.isLoggedIn) {
showDashboard();
}
// Do this:
user.isLoggedIn && showDashboard(); // Calls the function only if the condition is true
🔹 How it works: If user.isLoggedIn is true, JavaScript will execute showDashboard(). Otherwise, it does nothing.
2. Optional Chaining (No More TypeErrors!)
How many times have you seen this dreaded error?
❌ "Cannot read properties of undefined"
With optional chaining (?.), you can safely access deeply nested properties without crashing your app.
console.log(user?.profile?.email ?? "Email not available");
🔹 If user.profile.email exists, it prints the email.
🔹 If any part is undefined, it safely returns "Email not available".
🔹 The ?? (Nullish Coalescing) ensures default values when properties don’t exist.
3. Swap Two Variables Without a Third Variable
Want to swap two values without creating a temporary variable? Try array destructuring!
let a = 10, b = 20;
[a, b] = [b, a];
console.log(a, b); // 20, 10
🔹 No need for an extra variable! JavaScript swaps them in one line.
4. Convert Any Value to Boolean Instantly!
Need to check if a value is truthy or falsy? Just use double NOT (!!)
console.log(!!"hello"); // true
console.log(!!0); // false
console.log(!!null); // false
console.log(!!""); // false
🔹 This is a quick way to convert any value to true or false without an explicit if check.
5. Generate an Array of Numbers in Seconds
Instead of writing loops to create an array of numbers, use Array.from()!
const numbers = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(numbers); // [1, 2, 3, 4, 5]
🔹 How it works:
{ length: 5 } creates an empty array with 5 slots.
(_, i) => i + 1 fills it with numbers 1 to 5.
Way shorter than writing a loop!
6. Flatten a Deeply Nested Array in One Line
Instead of writing recursive functions to flatten arrays, use .flat()!
const arr = [1, [2, [3, [4, 5]]]];
console.log(arr.flat(Infinity)); // [1, 2, 3, 4, 5]
🔹 The flat(Infinity) removes all levels of nesting.
🔹 Super useful when dealing with complex arrays!
**7. Randomize an Array (Fisher-Yates Shuffle) 🎲
**Want to shuffle an array like a deck of cards? Use the Fisher-Yates Shuffle!
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
console.log(shuffle([1, 2, 3, 4, 5]));
✅ Properly randomizes the array
✅ Unbiased & efficient (O(n) time complexity)
✅ Perfect for games, quizzes, or randomizing data!
8. Remove Duplicates from an Array Instantly
No need for loops! Use Set to remove duplicates in one line.
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]
🔹 Why it works: The Set object only stores unique values.
9. Fetch API Data in a Single Line
Instead of writing a multi-line fetch(), use async/await in one go!
const getUsers = async () => (await fetch("https://jsonplaceholder.typicode.com/users")).json();
🔹 This fetches and parses JSON in one step.
🔹 No need for extra .then() chaining!
Conclusion: JavaScript is Full of Magic!
These tiny tricks can make your code cleaner, shorter, and more efficient. Try using them in your next project!
💡 Which trick surprised you the most? Do you have a favorite JavaScript magic trick? Drop it in the comments! 👇 🚀
Hi.. I have just completed js, I hope I've got a mentor to lead me..I haven't built any project on it are there any suggestions from you about projects for me..