DEV Community

Preeti yadav
Preeti yadav

Posted on • Edited on

Small JavaScript Tricks That Feel Like Magic πŸͺ„

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

Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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");
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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

Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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]
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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]
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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]));
Enter fullscreen mode Exit fullscreen mode

βœ… 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]
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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();

Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

The array randomisation you show is not the Fisher Yates shuffle

Collapse
 
preeti_yadav profile image
Preeti yadav

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.

Collapse
 
krishn_05 profile image
krishn

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..

Collapse
 
preeti_yadav profile image
Preeti yadav

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! πŸš€