DEV Community

Cover image for 30 Killer JavaScript One-Liners That’ll Make You Look Like a Pro 😎
TAQUI ⭐
TAQUI ⭐

Posted on

30 Killer JavaScript One-Liners That’ll Make You Look Like a Pro 😎

TL;DR

JavaScript has some really cool abilities that allow you to do amazing things with just a single line of code. Here are 30 useful JavaScript one-liners explained simply for both beginners and pros alike! Get ready to impress your friends with your JavaScript skills. 😎

Hey friends, its me Md Taqui Imam self taught full stack developer and tech writer. This Blog is specially for beginners.

Follow me in Github

So, let's get started🎉

Sure, here are in-depth one-liner JavaScript tricks for each of the 30 tasks:

1️⃣ Copy content to the clipboard:

   const copyToClipboard = text => { const el = document.createElement("textarea"); el.value = text; document.body.appendChild(el); el.select(); document.execCommand("copy"); document.body.removeChild(el); };
Enter fullscreen mode Exit fullscreen mode

2️⃣ Shuffle an array:

   const shuffleArray = arr => arr.sort(() => Math.random() - 0.5);
Enter fullscreen mode Exit fullscreen mode

3️⃣ Generate a random password:

   const generatePassword = length => Array.from({ length }, () => String.fromCharCode(Math.floor(Math.random() * 94) + 33)).join('');
Enter fullscreen mode Exit fullscreen mode

4️⃣ Get the mouse selection:

   const getSelectedText = () => window.getSelection().toString();
Enter fullscreen mode Exit fullscreen mode

5️⃣ Check if a string is a palindrome:

   const isPalindrome = str => str === str.split('').reverse().join('');
Enter fullscreen mode Exit fullscreen mode

6️⃣ Calculate the sum of all prime numbers up to a given number:

   const isPrime = num => { for(let i = 2; i < num; i++) if(num % i === 0) return false; return num > 1; };
   const sumPrimes = n => Array.from({ length: n }, (_, i) => isPrime(i) ? i : 0).reduce((a, b) => a + b);
Enter fullscreen mode Exit fullscreen mode

7️⃣ Create a simple countdown timer:

   const countdown = (seconds, callback) => { const interval = setInterval(() => { if (seconds === 0) { clearInterval(interval); callback(); } seconds--; }, 1000); };
Enter fullscreen mode Exit fullscreen mode

8️⃣ Implement a basic calculator:

   const basicCalculator = (a, operator, b) => operator === '+' ? a + b : operator === '-' ? a - b : operator === '*' ? a * b : operator === '/' ? a / b : 'Invalid operator';
Enter fullscreen mode Exit fullscreen mode

9️⃣ Validate an email address:

   const isEmailValid = email => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
Enter fullscreen mode Exit fullscreen mode

🔟 Checking that is the number is even or odd:

const isEven = num => num % 2 === 0;
Enter fullscreen mode Exit fullscreen mode

11. Generate a UUID (Universally Unique Identifier):

const generateUUID = () => 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => (Math.random() * 16 | 0).toString(16));
Enter fullscreen mode Exit fullscreen mode

12. Extract the file extension from a URL:

const getFileExtension = url => url.split('.').pop();
Enter fullscreen mode Exit fullscreen mode

13. Calculate the distance between two coordinates (latitude and longitude):

const calculateDistance = (lat1, lon1, lat2, lon2) => { const rad = x => x * Math.PI / 180; const R = 6371; const dLat = rad(lat2 - lat1); const dLon = rad(lon2 - lon1); return R * 2 * Math.asin(Math.sqrt(Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * Math.sin(dLon/2) * Math.sin(dLon/2))); };
Enter fullscreen mode Exit fullscreen mode

14. Encode and decode a URL:

const encodedURL = encodeURIComponent("your_url");
const decodedURL = decodeURIComponent(encodedURL);
Enter fullscreen mode Exit fullscreen mode

15. Find the intersection of two arrays:

const intersection = (arr1, arr2) => arr1.filter(value => arr2.includes(value));
Enter fullscreen mode Exit fullscreen mode

16. Sort an array of objects by a specific property:

const sortByProperty = (arr, prop) => arr.sort((a, b) => a[prop] > b[prop] ? 1 : -1);
Enter fullscreen mode Exit fullscreen mode

17. Remove duplicate values from an array:

const removeDuplicates = arr => Array.from(new Set(arr));
Enter fullscreen mode Exit fullscreen mode

18. Create a simple to-do list with local storage:

const todoList = JSON.parse(localStorage.getItem('todos')) || [];
    // Adding a new task to the Todo-list
    todoList.push(newTask);
    // Save the updated list in local storage
    localStorage.setItem('todos', JSON.stringify(todoList));
Enter fullscreen mode Exit fullscreen mode

19. Convert rgba to hexadecimal:

const rgbaToHex = (r, g, b, a) => `#${(1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1)}`;
Enter fullscreen mode Exit fullscreen mode

20. Find the longest word in a sentence:

const findLongestWord = sentence => sentence.split(' ').reduce((longest, word) => word.length > longest.length ? word : longest);
Enter fullscreen mode Exit fullscreen mode

21. Calculate the age based on a birthdate:

const calculateAge = birthdate => Math.floor((new Date() - new Date(birthdate)) / 31557600000);
Enter fullscreen mode Exit fullscreen mode

22. Check if a number is prime number or not:

const isPrime = num => { for(let i = 2; i < num; i++) if(num % i === 0) return false; return num > 1; };
Enter fullscreen mode Exit fullscreen mode

23. Convert a timestamp to a human-readable date:

const formatDate = timestamp => new Date(timestamp).toLocaleDateString();
Enter fullscreen mode Exit fullscreen mode

24. Get the average of multiple numbers:

const calculateAverage = numbers => numbers.reduce((total, num) => total + num, 0) / numbers.length;
Enter fullscreen mode Exit fullscreen mode

25. Display a random quote on a webpage:

const quotes = ["Quote 1", "Quote 2", "Quote 3"];
const randomQuote = quotes[Math.floor(Math.random() * quotes.length)];
Enter fullscreen mode Exit fullscreen mode

26. Implement a basic digital clock:

const updateClock = () => { const now = new Date(); const time = now.toLocaleTimeString(); document.getElementById("clock").textContent = time; };
    setInterval(updateClock, 1000);
Enter fullscreen mode Exit fullscreen mode

27. Perform basic CRUD operations with local storage:

    // Create
    localStorage.setItem('key', 'value');
    // Read
    const value = localStorage.getItem('key');
    // Update
    localStorage.setItem('key', 'new_value');
    // Delete
    localStorage.removeItem('key');
Enter fullscreen mode Exit fullscreen mode

28. Convert hexadecimal to rgba:

    const hexToRGBA = hex => { const bigint = parseInt(hex, 16); const r = (bigint >> 16) & 255; const g = (bigint >> 8) & 255; const b = bigint & 

255; return `rgba(${r}, ${g}, ${b}, 1)`; };
Enter fullscreen mode Exit fullscreen mode

29. Generate a QR code from text:

const generateQRCode = text => { const qr = new QRCode(document.getElementById("qrcode"), { text: text, width: 128, height: 128 }); };
Enter fullscreen mode Exit fullscreen mode

30. Display a "Hello, World!" popup on a webpage:

    alert("Hello, World!");
Enter fullscreen mode Exit fullscreen mode

The End 🚀

i hope you find this blog helpful and learned something new .

Don't forget to Drop 💖🔥🦄,

Written By Md Taqui Imam

Follow me in Github

Happy Coding👋

Top comments (19)

Collapse
 
frankwisniewski profile image
Frank Wisniewski

If you put several commands in one line, separated by semicolons, it is not a one-liner

Collapse
 
moopet profile image
Ben Sinclair

I ran uglify on my codebase and now my entire app is apparently a one-liner!

Collapse
 
best_codes profile image
Best Codes

IKR xD

Collapse
 
best_codes profile image
Best Codes

Couldn't agree with you more.

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

LOL! #1 a one-liner?? Bro, get serious.

Collapse
 
best_codes profile image
Best Codes

IT is AI written, that's the problem. I agree with you though.

Collapse
 
crespire profile image
crespire • Edited

I would probably not generate UUIDs this way. Use a library. While I am not an expert in this area, I am pretty sure a bit more goes into a UUID than what you've shown.

Just look at the source for the UUID package on NPM, it is not as simple as random characters: github.com/uuidjs/uuid/tree/main/src

Collapse
 
vladern profile image
vladyslav kuchmenko

There is a better way with crypto.randomUUID() it has good support in modern browsers developer.mozilla.org/en-US/docs/W...

Collapse
 
crespire profile image
crespire

Yes, the UUID library wraps this where it is available.

Collapse
 
dannickbedard profile image
Dannick Bedard

Uuid should be unique. This math random has a small chance of generating the same output more than one. :D

Collapse
 
manchicken profile image
Mike Stemle

It’s frustrating to see so many articles listing stuff without adding any value. You don’t cover how these work for folks, and I’m not sure memorizing a list of snippets is as helpful.

Collapse
 
best_codes profile image
Best Codes

The codes are AI written. Still cool though. The "Sure! .... " gives it away.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
best_codes profile image
Best Codes

Um, what does that mean? I don't understand what you are saying…

Collapse
 
best_codes profile image
Best Codes

And I don't know if "alert("Hello, world!"); is all that killer. That was the first JS code I ever ran I think.

Collapse
 
syeo66 profile image
Red Ochsenbein (he/him)

Uh. Did not like my comment? How about challenging it and starting to discuss?

Collapse
 
best_codes profile image
Best Codes

Why would someone do that? :D

Collapse
 
vladern profile image
vladyslav kuchmenko
  1. To generate a random UUID I recommend using crypto.randomUUID() method it has pretty good support for modern browsers: developer.mozilla.org/en-US/docs/W...
Collapse
 
syeo66 profile image
Info Comment hidden by post author - thread only accessible via permalink
Red Ochsenbein (he/him) • Edited

"...That’ll Make You Look Like a Pro" I'm afraid the contrary is true. If someone in my team would come up with some of those, I'd have them think hard about what it means to be a pro within a team...

Some comments have been hidden by the post's author - find out more