25 Killer JavaScript One-Liners: Supercharge Your Code and Impress Your Peers

Level Up Your JavaScript Skills

1. Check if a string is empty:

!str.trim()

2. Reverse a string:

str.split("").reverse().join("")

3. Check if an object is empty:

Object.keys(obj).length === 0

4. Get the last element of an array:

arr[arr.length - 1]

5. Shuffle an array:

arr.sort(() => Math.random() - 0.5)

6. Deep clone an object:

JSON.parse(JSON.stringify(obj))

7. Flatten an array:

arr.flat(Infinity)

8. Get the sum of all elements in an array:

arr.reduce((acc, curr) => acc + curr, 0)

9. Remove duplicates from an array:

arr.filter((item, idx) => arr.indexOf(item) === idx)

10. Check if a value is a number:

!isNaN(Number(value))

11. Debounce a function:

function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

12. Throttle a function:

function throttle(fn, delay) {
  let lastCall;
  return (...args) => {
    const now = Date.now();
    if (lastCall && now < lastCall + delay) {
      return;
    }
    lastCall = now;
    fn(...args);
  };
}

13. Get the URL parameters:

new URLSearchParams(window.location.search)

14. Convert a string to camelCase:

const camelCase = str => str.replace(/[^a-zA-Z0-9]+(.)/g, (m, char) => char.toUpperCase());

15.Convert a string to snake_case:

const snakeCase = str => str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();

Create a unique ID:

Math.floor(Math.random() * 1000000000)

17. Check if a variable is defined:

typeof variable !== 'undefined'

18. Check if a variable is null:

variable === null

19. Check if a variable is undefined:

typeof variable === 'undefined'

20. Currying a function:

const curry = (fn, ...args1) => (...args2) => fn(...args1, ...args2);

21. Memoization:

function memoize(fn) {
  const cache = {};
  return (...args) => {
    const key = JSON.stringify(args);
    if (cache[key]) {
      return cache[key];
    }
    const result = fn(...args);
    cache[key] = result;
    return result;
  };
}

22. Get a random element from an array:

arr[Math.floor(Math.random() * arr.length)]

23. Convert a number to a string with commas:

const numberWithCommas = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');

24. Convert a string to a number:

Number(str)

25. Check if a string is a palindrome:

str === str.split("").reverse().join("")

Did you find this article valuable?

Support Narayana M V L by becoming a sponsor. Any amount is appreciated!