DEV Community

Cover image for Top 50 One-Liners JavaScript
Sh Raj
Sh Raj

Posted on • Updated on • Originally published at codexdindia.blogspot.com

Top 50 One-Liners JavaScript

Mastering JavaScript: Top 50 One-Liners Every Developer Should Know

Know More :- https://codexdindia.blogspot.com/2024/02/top-50-one-liners-javascript.html
Join Discord πŸš€ :- https://discord.gg/26DFm2rku9

Introduction:

JavaScript is a versatile and powerful programming language used extensively in web development. Whether you're a seasoned developer or just starting your journey, mastering JavaScript can significantly boost your productivity and efficiency. In this article, we'll explore the top 50 JavaScript one-liners that every developer should know. These concise and elegant solutions cover a wide range of common tasks, from manipulating arrays to working with strings and objects.

1. Checking if a Variable is Undefined:

const isUndefined = variable => typeof variable === 'undefined';
Enter fullscreen mode Exit fullscreen mode

2. Checking if a Variable is Null:

const isNull = variable => variable === null;
Enter fullscreen mode Exit fullscreen mode

3. Checking if a Variable is Empty:

const isEmpty = variable => !variable;
Enter fullscreen mode Exit fullscreen mode

4. Checking if a Variable is an Array:

const isArray = variable => Array.isArray(variable);
Enter fullscreen mode Exit fullscreen mode

5. Checking if a Variable is an Object:

const isObject = variable => typeof variable === 'object' && variable !== null;
Enter fullscreen mode Exit fullscreen mode

6. Checking if a Variable is a Function:

const isFunction = variable => typeof variable === 'function';
Enter fullscreen mode Exit fullscreen mode

7. Getting the Last Element of an Array:

const lastElement = array => array.slice(-1)[0];
Enter fullscreen mode Exit fullscreen mode

8. Flattening an Array:

const flattenArray = array => array.flat();
Enter fullscreen mode Exit fullscreen mode

9. Reversing a String:

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

10. Generating a Random Number:

const randomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
Enter fullscreen mode Exit fullscreen mode

11. Removing Duplicates from an Array:

const removeDuplicates = array => [...new Set(array)];
Enter fullscreen mode Exit fullscreen mode

12. Checking if an Array Contains a Specific Value:

const containsValue = (array, value) => array.includes(value);
Enter fullscreen mode Exit fullscreen mode

13. Checking if a String Contains a Substring:

const containsSubstring = (str, substring) => str.includes(substring);
Enter fullscreen mode Exit fullscreen mode

14. Getting the Current Date and Time:

const currentDateTime = () => new Date().toLocaleString();
Enter fullscreen mode Exit fullscreen mode

15. Checking if a Year is a Leap Year:

const isLeapYear = year => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
Enter fullscreen mode Exit fullscreen mode

16. Truncating a Number to a Specified Decimal Place:

const truncateNumber = (num, decimalPlaces) => Math.trunc(num * 10 ** decimalPlaces) / 10 ** decimalPlaces;
Enter fullscreen mode Exit fullscreen mode

17. Checking if an Object has a Specific Property:

const hasProperty = (obj, property) => obj.hasOwnProperty(property);
Enter fullscreen mode Exit fullscreen mode

18. Converting a String to Title Case:

const toTitleCase = str => str.replace(/\b\w/g, char => char.toUpperCase());
Enter fullscreen mode Exit fullscreen mode

19. Repeating a String N Times:

const repeatString = (str, n) => str.repeat(n);
Enter fullscreen mode Exit fullscreen mode

20. Generating a Range of Numbers:

const range = (start, end) => Array.from({ length: end - start + 1 }, (_, i) => start + i);
Enter fullscreen mode Exit fullscreen mode

21. Summing Numbers in an Array:

const sumArray = array => array.reduce((acc, curr) => acc + curr, 0);
Enter fullscreen mode Exit fullscreen mode

22. Getting the Maximum Value in an Array:

const maxArrayValue = array => Math.max(...array);
Enter fullscreen mode Exit fullscreen mode

23. Getting the Minimum Value in an Array:

const minArrayValue = array => Math.min(...array);
Enter fullscreen mode Exit fullscreen mode

24. Checking if a Number is Even:

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

25. Checking if a Number is Odd:

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

26. Checking if a String is Palindrome:

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

27. Reversing the Order of Words in a String:

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

28. Checking if a Number is Prime:

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

29. Converting Fahrenheit to Celsius:

const fahrenheitToCelsius = f => (f - 32) * 5 / 9;
Enter fullscreen mode Exit fullscreen mode

30. Converting Celsius to Fahrenheit:

const celsiusToFahrenheit = c => (c * 9 / 5) + 32;
Enter fullscreen mode Exit fullscreen mode

31. Factorial of a Number:

const factorial = n => n === 0 ? 1 : n * factorial(n - 1);
Enter fullscreen mode Exit fullscreen mode

32. Fibonacci Sequence:

const fibonacci = n => n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
Enter fullscreen mode Exit fullscreen mode

33. Finding the Greatest Common Divisor (GCD) of Two Numbers:

const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
Enter fullscreen mode Exit fullscreen mode

34. Finding the Least Common Multiple (LCM) of Two Numbers:

const lcm = (a, b) => (a * b) / gcd(a, b);
Enter fullscreen mode Exit fullscreen mode

34. Shuffle an Array:

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

35. Checking if a Number is a Perfect Square:

const isPerfectSquare = num => Math.sqrt(num) % 1 === 0;
Enter fullscreen mode Exit fullscreen mode

36. Checking if a Number is a Power of Two:

const isPowerOfTwo = num => (num & (num - 1)) === 0 && num !== 0;
Enter fullscreen mode Exit fullscreen mode

37. Checking if a Number is a Palindrome:

const isPalindromeNumber = num => num.toString() === num.toString().split('').reverse().join('');
Enter fullscreen mode Exit fullscreen mode

38. Capitalize the First Letter of Each Word in a Sentence:

const capitalizeWords = sentence => sentence.replace(/\b\w/g, char => char.toUpperCase());
Enter fullscreen mode Exit fullscreen mode

39. Counting the Occurrences of Each Element in an Array:

const countOccurrences = array => array.reduce((acc, val) => {
  acc[val] = (acc[val] || 0) + 1;
  return acc;
}, {});
Enter fullscreen mode Exit fullscreen mode

40. Sum of Squares of Digits of a Number:

const sumOfSquareDigits = num => num.toString().split('').reduce((acc, digit) => acc + Math.pow(parseInt(digit), 2), 0);
Enter fullscreen mode Exit fullscreen mode

41. Converting a Number to Binary:

const toBinary = num => num.toString(2);
Enter fullscreen mode Exit fullscreen mode

42. Converting a Binary Number to Decimal:

const binaryToDecimal = binary => parseInt(binary, 2);
Enter fullscreen mode Exit fullscreen mode

43. Checking if a String is an Anagram of Another String:

const isAnagram = (str1, str2) => str1.split('').sort().join('') === str2.split('').sort().join('');
Enter fullscreen mode Exit fullscreen mode

44. Converting an Object to Query Parameters String:

const objectToQueryString = obj => Object.entries(obj).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join('&');
Enter fullscreen mode Exit fullscreen mode

45. Checking if a Year is a Leap Year (Using Ternary Operator):

const isLeapYear = year => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? true : false;
Enter fullscreen mode Exit fullscreen mode

46. Reversing an Array in Place:

const reverseArrayInPlace = array => array.reverse();
Enter fullscreen mode Exit fullscreen mode

47. Finding the Maximum Value in an Array (Using Spread Operator):

const maxArrayValue = array => Math.max(...array);
Enter fullscreen mode Exit fullscreen mode

48. Finding the Minimum Value in an Array (Using Spread Operator):

const minArrayValue = array => Math.min(...array);
Enter fullscreen mode Exit fullscreen mode

49. Truncating a String to a Maximum Length and Appending Ellipsis:

const truncateString = (str, maxLength) => str.length > maxLength ? str.slice(0, maxLength) + '...' : str;
Enter fullscreen mode Exit fullscreen mode

50. Finding the Longest Word in a Sentence:

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

Conclusion:
JavaScript one-liners are concise and powerful solutions to common programming tasks. By mastering these one-liners, you can write cleaner, more efficient code and become a more proficient JavaScript developer. Experiment with these examples and incorporate them into your projects to take your coding skills to the next level. Happy coding!

Top comments (5)

Collapse
 
manchicken profile image
Info Comment hidden by post author - thread only accessible via permalink
Mike Stemle

So many of these are wrong. #5 will return true for Date and #13 actually takes more work to use as a one liner than it would just use String.includes().

Collapse
 
jonrandy profile image
Info Comment hidden by post author - thread only accessible via permalink
Jon Randy πŸŽ–οΈ • Edited

They're wrong because they're most likely straight out of ChatGPT (or similar), and the author has not checked them before posting. Try entering the following into ChatGPT:

Write an article titled "Mastering JavaScript: Top 50 One-Liners Every Developer Should Know"

You'll get many of the same examples, with the same mistakes.

Collapse
 
eerk profile image
eerk

point 7 has been made easer : lastElement = array.at(-1)

Collapse
 
darkwiiplayer profile image
Info Comment hidden by post author - thread only accessible via permalink
π’ŽWii πŸ³οΈβ€βš§οΈ

As always with these one-liners, whether one should "know" about them or actually use them are two entirely different questions.

To anyone looking at these and thinking about actually using them in real life, here's a couple things to consider:

Obfuscation

Taking a simple comparison like value === undefined (no, you don't need the typeof) and hiding it in a function does almost nothing to shorten the code, but hides what's actually going on, so anyone reading the code will have to jump to the definition instead of just reading what happens.

The same applies to redefining standard functions like const isArray = variable => Array.isArray(variable); (or, if you want to save typing, const {isArray} = Array. If you see Array.isArray(object) you know exactly what it does, or you can directly google it. If you see isArray(object), you'll have to jump to the definition first.

Pointless Code

Looking at an example like this:

const isObject = variable => typeof variable === 'object' && variable !== null;
Enter fullscreen mode Exit fullscreen mode

this could be simplified a fair bit by taking into consideration that something of type 'object' is only falsey if it is null, so this can be shortened to variable && typeof variable == "object"

Use === if it gives you or your linter peace of mind, but typeof always returns a string and the rhs is a constant, so it doesn't really change anything.

An extreme example: Compare flattenArray(array) to array.flat(). You type more by wrapping that in a function, and obfuscate what happens.

Pointless Complexity

The best way to do a thing is sometimes just the straight-forward solution.

If you want to get the last element of an array, just index it with its length + 1, and your code will be much easier to read. You'll also avoid allocating a new single-element array, which would the be up to your VM to optimise away in the best case or to garbage-collect in the worst.

Also, Array.prototype.at() is a thing; you can just use my_array.at(-1) and everyone can understand what it does as long as they know the standard functions well enough.

Other Nitpicks

hasProperty doesn't do what it says and can crash your code:

const p = document.createElement("p")
p.hasOwnProperty("lang") // false
"lang" in p // true

const o = Object.create(null)
"hasOwnProperty" in o // false
Reflect.hasOwnProperty.call(o, "hasOwnProperty") // false
o.hasOwnProperty("hasOwnProperty") // TypeError: o.hasOwnProperty is not a function
Enter fullscreen mode Exit fullscreen mode

The one about the palindrome would be a good starting point for an interview question: How could this function be optimised? The answer is, you only need to compare the first half to the latter half. Mirroring and comparing means every character gets compared twice.

Also that fibonacci function is half a fork bomb. Don't do fibonacci like that, you can literally google how to do it correctly (even recursively) in like 5 minutes.

Same for shuffling an array. That's gonna perform really poorly for large arrays.

Counting the occurrences of an element has a subtle but funny bug because it uses a plain Object without setting its prototype to null:

countOccurrences(["foo", "bar", "foo", "hasOwnProperty"])
// {foo: 2, bar: 1, hasOwnProperty: 'function hasOwnProperty() { [native code] }1'}
Enter fullscreen mode Exit fullscreen mode

For query parameters, just use URLSearchParams:

new URLSearchParams({foo: "foo", bar: "bar"}).toString()
// foo=foo&bar=bar
Enter fullscreen mode Exit fullscreen mode

And lastly, the most nitpicky one of them all: The longest word function will count words followed by a comma as one character longer than they are. Same for any special character, actually.


In conclusion, don't take any of these as examples for how to do things. Many of those would make for really good interview questions though. "What can you say about this function?" type stuff.

Collapse
 
jonrandy profile image
Info Comment hidden by post author - thread only accessible via permalink
Jon Randy πŸŽ–οΈ

AI generated/assisted posts should adhere to the guidelines for such content.

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