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.
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); };
2️⃣ Shuffle an array:
const shuffleArray = arr => arr.sort(() => Math.random() - 0.5);
3️⃣ Generate a random password:
const generatePassword = length => Array.from({ length }, () => String.fromCharCode(Math.floor(Math.random() * 94) + 33)).join('');
4️⃣ Get the mouse selection:
const getSelectedText = () => window.getSelection().toString();
5️⃣ Check if a string is a palindrome:
const isPalindrome = str => str === str.split('').reverse().join('');
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);
7️⃣ Create a simple countdown timer:
const countdown = (seconds, callback) => { const interval = setInterval(() => { if (seconds === 0) { clearInterval(interval); callback(); } seconds--; }, 1000); };
8️⃣ Implement a basic calculator:
const basicCalculator = (a, operator, b) => operator === '+' ? a + b : operator === '-' ? a - b : operator === '*' ? a * b : operator === '/' ? a / b : 'Invalid operator';
9️⃣ Validate an email address:
const isEmailValid = email => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
🔟 Checking that is the number is even or odd:
const isEven = num => num % 2 === 0;
11. Generate a UUID (Universally Unique Identifier):
const generateUUID = () => 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => (Math.random() * 16 | 0).toString(16));
12. Extract the file extension from a URL:
const getFileExtension = url => url.split('.').pop();
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))); };
14. Encode and decode a URL:
const encodedURL = encodeURIComponent("your_url");
const decodedURL = decodeURIComponent(encodedURL);
15. Find the intersection of two arrays:
const intersection = (arr1, arr2) => arr1.filter(value => arr2.includes(value));
16. Sort an array of objects by a specific property:
const sortByProperty = (arr, prop) => arr.sort((a, b) => a[prop] > b[prop] ? 1 : -1);
17. Remove duplicate values from an array:
const removeDuplicates = arr => Array.from(new Set(arr));
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));
19. Convert rgba to hexadecimal:
const rgbaToHex = (r, g, b, a) => `#${(1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1)}`;
20. Find the longest word in a sentence:
const findLongestWord = sentence => sentence.split(' ').reduce((longest, word) => word.length > longest.length ? word : longest);
21. Calculate the age based on a birthdate:
const calculateAge = birthdate => Math.floor((new Date() - new Date(birthdate)) / 31557600000);
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; };
23. Convert a timestamp to a human-readable date:
const formatDate = timestamp => new Date(timestamp).toLocaleDateString();
24. Get the average of multiple numbers:
const calculateAverage = numbers => numbers.reduce((total, num) => total + num, 0) / numbers.length;
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)];
26. Implement a basic digital clock:
const updateClock = () => { const now = new Date(); const time = now.toLocaleTimeString(); document.getElementById("clock").textContent = time; };
setInterval(updateClock, 1000);
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');
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)`; };
29. Generate a QR code from text:
const generateQRCode = text => { const qr = new QRCode(document.getElementById("qrcode"), { text: text, width: 128, height: 128 }); };
30. Display a "Hello, World!" popup on a webpage:
alert("Hello, World!");
The End 🚀
i hope you find this blog helpful and learned something new .
Don't forget to Drop 💖🔥🦄,
Written By Md Taqui Imam
Top comments (19)
If you put several commands in one line, separated by semicolons, it is not a one-liner
I ran uglify on my codebase and now my entire app is apparently a one-liner!
IKR xD
Couldn't agree with you more.
LOL! #1 a one-liner?? Bro, get serious.
IT is AI written, that's the problem. I agree with you though.
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
There is a better way with
crypto.randomUUID()
it has good support in modern browsers developer.mozilla.org/en-US/docs/W...Yes, the UUID library wraps this where it is available.
Uuid should be unique. This math random has a small chance of generating the same output more than one. :D
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.
The codes are AI written. Still cool though. The "Sure! .... " gives it away.
Um, what does that mean? I don't understand what you are saying…
And I don't know if "alert("Hello, world!"); is all that killer. That was the first JS code I ever ran I think.
Uh. Did not like my comment? How about challenging it and starting to discuss?
Why would someone do that? :D
crypto.randomUUID()
method it has pretty good support for modern browsers: developer.mozilla.org/en-US/docs/W..."...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