CodersTechZone
  • .NET
    • C#
    • ASP.Net
  • HTML
  • Javascript
  • CSS
  • Database
    • SQL Server
    • MYSql
    • Oracle
  • AI
  • TechNews
  • Web-Stories

10 JavaScript One-Liners That Will Blow Your Mind in 2025

Shawpnendu Bikash Maloroy

February 28, 2025
10 JavaScript One-Liners That Will Blow Your Mind in 2025
Spread the love

JavaScript is a powerful language. Most of times we are writing long and complex code to get things done. But we have to keep in mind that In fact, we can achieve a lot with just one line of JS code! 🚀

In this article, we will explore 10 mind-blowing JavaScript one-liners that will save our time and make coding fun. Let’s dive in without wasting any time!

Table of Contents

  • 1. Reverse a String Instantly
  • 2. Check if a Number is Even or Odd
  • 3. Shuffle an Array (Fisher-Yates Algorithm)
  • 4. Remove Duplicates from an Array
  • 5. Find the Maximum Number in an Array
  • 6. Generate a Random Hex Color
  • 7. Convert a String to Title Case
  • 8. Get the Current Timestamp
  • 9. Convert an Object to a Query String
  • 10. Count Occurrences of Elements in an Array
  • JavaScript One-Liners – List of Code Example:
  • Why These One-Liners Are Useful
  • Frequently Asked Questions (FAQ)
    • 1. Are JavaScript one-liners efficient?
    • 2. Will these one-liners work in all browsers?
    • 3. Can I use these one-liners in real-world projects?
    • 4. How can I learn more JavaScript tricks?
  • Conclusion

1. Reverse a String Instantly

Want to reverse a string in JavaScript? You don’t need loops. Just use one simple line like below:

const reverseString = str => str.split('').reverse().join('');
console.log(reverseString("JavaScript")); // tpircSavaJ
JavaScript One-Liner to reverse a string

This code breaks the string into an array, reverses it, and joins it back. It’s a quick way to reverse any string!

2. Check if a Number is Even or Odd

Instead of using an if-else statement, use this simple one-liner:

const isEven = num => num % 2 === 0;
console.log(isEven(10)); // true
Check if a Number is Even or Odd

NOTE

This checks the last binary digit of a number. If it’s 0, the number is even; otherwise, it’s odd. Super fast!

3. Shuffle an Array (Fisher-Yates Algorithm)

Want to randomly shuffle an array? Here is an smart way to do it using one line:

const shuffleArray = arr => arr.sort(() => Math.random() - 0.5);
console.log(shuffleArray([1, 2, 3, 4, 5]));
Shuffle an Array

This randomizes the order of elements in an array, useful for games, quizzes, and more!

4. Remove Duplicates from an Array

Instead of using loops, use the Set object and make your code one liner. Amazing right?

const uniqueArray = arr => [...new Set(arr)];
console.log(uniqueArray([1, 2, 2, 3, 4, 4, 5])); // [1, 2, 3, 4, 5]
Remove Duplicates

The Set object automatically removes duplicates, making this the easiest way to get unique values.

5. Find the Maximum Number in an Array

Forget the for loop—use Math.max and spread operator:

const maxNumber = arr => Math.max(...arr);
console.log(maxNumber([10, 20, 5, 8])); // 20
Find the Maximum Number in an Array

This quickly finds the largest number in an array by spreading all values into Math.max().

6. Generate a Random Hex Color

Want a random color in one line using JavaScript?

const randomColor = () => `#${Math.floor(Math.random()*16777215).toString(16)}`;
console.log(randomColor());
Generate a Random Hex Color

This generates a six-digit hex color code, perfect for styling elements dynamically.

7. Convert a String to Title Case

Make the first letter of every word uppercase with this simple JS function:

const toTitleCase = str => str.replace(/\b\w/g, char => char.toUpperCase());
console.log(toTitleCase("hello world")); // Hello World
Convert a String to Title Case

This replaces the first letter of each word with its uppercase version. Great for formatting dashboard titles!

8. Get the Current Timestamp

No need to struggle with Date objects—use this shortcut instead:

const timestamp = () => Date.now();
console.log(timestamp());
Get the Current Timestamp

This returns the number of milliseconds since January 1, 1970. Useful for tracking time events.

9. Convert an Object to a Query String

Turn an object into a URL-friendly query string effortlessly like below:

const toQueryString = obj => new URLSearchParams(obj).toString();
console.log(toQueryString({ name: "John", age: 30 })); 
// name=John&age=30
Convert an Object to a Query String

This helps send object data in a URL format, which is useful for APIs and links.

10. Count Occurrences of Elements in an Array

Use reduce() to count items quickly. Easy right?

const countOccurrences = arr => arr.reduce((acc, item) => ((acc[item] = (acc[item] || 0) + 1), acc), {});
console.log(countOccurrences(["apple", "banana", "apple", "orange"]));
// { apple: 2, banana: 1, orange: 1 }
Count Occurrences using JS

This creates an object that counts how often each element appears in the array. Great for analytics!

JavaScript One-Liners – List of Code Example:

JavaScript One-LinersDescription
reverseString(str)Reverses a string
isEven(num)Checks if a number is even or odd
shuffleArray(arr)Shuffles an array randomly
uniqueArray(arr)Removes duplicates from an array
maxNumber(arr)Finds the maximum number in an array
randomColor()Generates a random hex color
toTitleCase(str)Converts a string to title case
timestamp()Gets the current timestamp
toQueryString(obj)Converts an object to a query string
countOccurrences(arr)Counts occurrences of elements in an array

Why These One-Liners Are Useful

  • Saves time: No need to write lengthy functions.
  • More readable: Cleaner and easier to understand.
  • Performance optimized: Uses JavaScript’s built-in features effectively.
  • Beginner-friendly: Great for learning core JS concepts quickly.

Frequently Asked Questions (FAQ)

1. Are JavaScript one-liners efficient?

Yes! Many of these one-liners use optimized built-in JavaScript methods, making our code more concise and efficient.

2. Will these one-liners work in all browsers?

Most of these work in all modern browsers. However, always check browser compatibility if you are using advanced ES6+ features.

3. Can I use these one-liners in real-world projects?

Absolutely! These tricks can simplify your code and make it more readable, especially for small utility JS functions.

4. How can I learn more JavaScript tricks?

Follow our coding blogs, practice with our examples like CodersTechZone, and experiment with different one-liners in your projects!

Conclusion

These JavaScript one-liners can make your coding life easier while keeping your code clean and efficient. Try them out in your next project and impress your friends with your JavaScript mastery! 🧙‍♂️

🔥 Which one-liner blew your mind the most? Let me know in the comments!

💡 Want more JavaScript tricks? Follow CodersTechZone for more awesome content!

Shawpnendu Bikash Maloroy
Shawpnendu Bikash Maloroy

🏋️‍♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨‍✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Spread the love
«Previous
Next»

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • 7 Weird JavaScript Tricks That Look Like Bugs
    7 Weird JavaScript Tricks That Look Like Bugs (#3 Will Shock You!)
  • Build a JavaScript Gamer Journal in 8 Lines
    🎮 Build a JavaScript Gamer Journal in 8 Lines: Track Your Wins Like a Pro! 🏆
  • JavaScript Pet Feeder Reminder in 7 Lines
    How to Code a Simple JavaScript Pet Feeder Reminder in 7 Lines: Feed Your Pet Like a Coding Boss! 🐶
  • 10-line calculator JavaScript
    Build a Simple Calculator in JavaScript: 10 Lines to Wow Your Friends!
  • JavaScript No-Code Automation
    JavaScript No-Code Automation: How to Replace Zapier with a Few Lines of Code

About-CodersTech Zone |  Contact |  Disclaimer |  Fact-Checking policy |  Affiliate Disclosure |  Privacy Policy

Copyright © 2024 CodersTechZone.com