30 Killer JavaScript One-Liners That’ll Make You Look Like a Pro 😎
Tags: javascript, webdev, programming, beginners
Published: 2023-10-29 06:52:33

## 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](https://bit.ly/mdTaquiImam) self taught full stack developer and tech writer. This Blog is specially for beginners.

{% cta https://github.com/taqui-786 %}Follow me in Github{% endcta %}



> **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:**
   ```javascript
   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:**
   ```javascript
   const shuffleArray = arr => arr.sort(() => Math.random() - 0.5);
   ```

3️⃣ **Generate a random password:**
   ```javascript
   const generatePassword = length => Array.from({ length }, () => String.fromCharCode(Math.floor(Math.random() * 94) + 33)).join('');
   ```

4️⃣ **Get the mouse selection:**
   ```javascript
   const getSelectedText = () => window.getSelection().toString();
   ```

5️⃣ **Check if a string is a palindrome:**
   ```javascript
   const isPalindrome = str => str === str.split('').reverse().join('');
   ```

6️⃣ **Calculate the sum of all prime numbers up to a given number:**
   ```javascript
   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:**
   ```javascript
   const countdown = (seconds, callback) => { const interval = setInterval(() => { if (seconds === 0) { clearInterval(interval); callback(); } seconds--; }, 1000); };
   ```

8️⃣ **Implement a basic calculator:**
   ```javascript
   const basicCalculator = (a, operator, b) => operator === '+' ? a + b : operator === '-' ? a - b : operator === '*' ? a * b : operator === '/' ? a / b : 'Invalid operator';
   ```

9️⃣ **Validate an email address:**
   ```javascript
   const isEmailValid = email => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
   ```

🔟 **Checking that is the number is even or odd:**

```javascript
const isEven = num => num % 2 === 0;
```

## 11. Generate a UUID (Universally Unique Identifier):
```javascript
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:
```javascript
const getFileExtension = url => url.split('.').pop();
```

## 13. Calculate the distance between two coordinates (latitude and longitude):
```javascript
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:
```javascript
const encodedURL = encodeURIComponent("your_url");
const decodedURL = decodeURIComponent(encodedURL);
```

## 15. Find the intersection of two arrays:
```javascript
const intersection = (arr1, arr2) => arr1.filter(value => arr2.includes(value));
```

## 16. Sort an array of objects by a specific property:
```javascript
const sortByProperty = (arr, prop) => arr.sort((a, b) => a[prop] > b[prop] ? 1 : -1);
```

## 17. Remove duplicate values from an array:
```javascript
const removeDuplicates = arr => Array.from(new Set(arr));
```

## 18. Create a simple to-do list with local storage:
```javascript
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:
```javascript
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:
```javascript
const findLongestWord = sentence => sentence.split(' ').reduce((longest, word) => word.length > longest.length ? word : longest);
```

## 21. Calculate the age based on a birthdate:
```javascript
const calculateAge = birthdate => Math.floor((new Date() - new Date(birthdate)) / 31557600000);
```

## 22. Check if a number is prime number or not:
```javascript
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:
```javascript
const formatDate = timestamp => new Date(timestamp).toLocaleDateString();
```

## 24. Get the average of multiple numbers:
```javascript
const calculateAverage = numbers => numbers.reduce((total, num) => total + num, 0) / numbers.length;
```

## 25. Display a random quote on a webpage:
```javascript
const quotes = ["Quote 1", "Quote 2", "Quote 3"];
const randomQuote = quotes[Math.floor(Math.random() * quotes.length)];
```

## 26. Implement a basic digital clock:
```javascript
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:
```javascript
    // 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:
```javascript
    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:
```javascript
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:
```javascript
    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](https://bit.ly/mdTaquiImam)**_

{% cta https://github.com/taqui-786 %}Follow me in Github{% endcta %}

## Happy Coding👋