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! π π
Top comments (4)
The array randomisation you show is not the Fisher Yates shuffle
You're absolutely right! The sort(() => Math.random() - 0.5) trick is often used to shuffle arrays, but it doesn't guarantee a perfectly uniform shuffle. The proper Fisher-Yates algorithm ensures every permutation is equally likely. Thanks for pointing it out! Iβll update the post to reflect that.
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..
Hey Krishn! First of all, congrats on completing JavaScript! Thatβs a big step, and I totally get how exciting it can feel when youβre figuring out what to build next.
If I were in your shoes, Iβd start with something small but usefulβmaybe a to-do list app or a weather app using an API. These helped me a lot when I was getting comfortable with JavaScript.
The key is to just start building! Even if itβs messy at first, youβll learn so much along the way. Feel free to reach out if you ever need help. You got this! π