Skip to main content

Top 50 One-Liners JavaScript

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

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';

2. Checking if a Variable is Null:

const isNull = variable => variable === null;

3. Checking if a Variable is Empty:

const isEmpty = variable => !variable;

4. Checking if a Variable is an Array:

const isArray = variable => Array.isArray(variable);

5. Checking if a Variable is an Object:

const isObject = variable => typeof variable === 'object' && variable !== null;

6. Checking if a Variable is a Function:

const isFunction = variable => typeof variable === 'function';

7. Getting the Last Element of an Array:

const lastElement = array => array.slice(-1)[0];

8. Flattening an Array:

const flattenArray = array => array.flat();

9. Reversing a String:

const reverseString = str => str.split('').reverse().join('');

10. Generating a Random Number:

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

11. Removing Duplicates from an Array:

const removeDuplicates = array => [...new Set(array)];

12. Checking if an Array Contains a Specific Value:

const containsValue = (array, value) => array.includes(value);

13. Checking if a String Contains a Substring:

const containsSubstring = (str, substring) => str.includes(substring);

14. Getting the Current Date and Time:

const currentDateTime = () => new Date().toLocaleString();

15. Checking if a Year is a Leap Year:

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

16. Truncating a Number to a Specified Decimal Place:

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

17. Checking if an Object has a Specific Property:

const hasProperty = (obj, property) => obj.hasOwnProperty(property);

18. Converting a String to Title Case:

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

19. Repeating a String N Times:

const repeatString = (str, n) => str.repeat(n);

20. Generating a Range of Numbers:

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

21. Summing Numbers in an Array:

const sumArray = array => array.reduce((acc, curr) => acc + curr, 0);

22. Getting the Maximum Value in an Array:

const maxArrayValue = array => Math.max(...array);

23. Getting the Minimum Value in an Array:

const minArrayValue = array => Math.min(...array);

24. Checking if a Number is Even:

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

25. Checking if a Number is Odd:

const isOdd = num => num % 2 !== 0;

26. Checking if a String is Palindrome:

const isPalindrome = str => str === str.split('').reverse().join('');

27. Reversing the Order of Words in a String:

const reverseWords = str => str.split(' ').reverse().join(' ');

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;
};

29. Converting Fahrenheit to Celsius:

const fahrenheitToCelsius = f => (f - 32) * 5 / 9;

30. Converting Celsius to Fahrenheit:

const celsiusToFahrenheit = c => (c * 9 / 5) + 32;

31. Factorial of a Number:

const factorial = n => n === 0 ? 1 : n * factorial(n - 1);

32. Fibonacci Sequence:

const fibonacci = n => n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);

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

const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);

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

const lcm = (a, b) => (a * b) / gcd(a, b);

34. Shuffle an Array:

const shuffleArray = array => array.sort(() => Math.random() - 0.5);

35. Checking if a Number is a Perfect Square:

const isPerfectSquare = num => Math.sqrt(num) % 1 === 0;

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

const isPowerOfTwo = num => (num & (num - 1)) === 0 && num !== 0;

37. Checking if a Number is a Palindrome:

const isPalindromeNumber = num => num.toString() === num.toString().split('').reverse().join('');

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

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

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;
}, {});

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);

41. Converting a Number to Binary:

const toBinary = num => num.toString(2);

42. Converting a Binary Number to Decimal:

const binaryToDecimal = binary => parseInt(binary, 2);

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

const isAnagram = (str1, str2) => str1.split('').sort().join('') === str2.split('').sort().join('');

44. Converting an Object to Query Parameters String:

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

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;

46. Reversing an Array in Place:

const reverseArrayInPlace = array => array.reverse();

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

const maxArrayValue = array => Math.max(...array);

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

const minArrayValue = array => Math.min(...array);

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

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

50. Finding the Longest Word in a Sentence:

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

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!

Comments

Popular posts from this blog

How to Add a VS Code Editor to Your Website

How to Add a VS Code Editor to Your Website The Monaco editor by Microsoft provides a code editor component that can be easily integrated into websites. With just a few lines of code, you can add a full-featured editor similar to VS Code in your web app. In this tutorial, we'll see how to do just that. Getting Started To use Monaco, we need to include it in our page. We can get it from a CDN: < script src = "https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.23.0/min/vs/loader.min.js" > </ script > This will load the Monaco library asynchronously. Next, we need a <div> in our HTML where we can instantiate the editor: < div id = "editor" ></ div > Now in our JavaScript code, we can initialize Monaco and create the editor: require .config({ paths : { 'vs' : 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.23.0/min/vs' }}); require ([ "vs/editor/editor.main" ], function ( ) { const ...

10 Free GitHub Copilot Alternatives for VS Code in 2024

10 Free GitHub Copilot Alternatives for VS Code in 2024 As developers, we're always on the lookout for tools that can help us write code more efficiently. GitHub Copilot has been a game-changer in this regard, but its premium pricing may be a deterrent for some. Fortunately, there are several free alternatives available that offer similar functionality. In this article, we'll explore 10 of the best free GitHub Copilot alternatives for Visual Studio Code in 2024. Comparison of Free GitHub Copilot Alternatives Tool Language Support Auto-Completion Code Generation Code Explanation Bito Python, JavaScript, TypeScript, Java, C#, C++, Go, Ruby, PHP, Swift, Kotlin, Rust, Scala ✓ ✓ ✓ Tabnine Python, JavaScript, TypeScript, Java, C#, C++, Go, Ruby, PHP, Swift, Kotlin, Rust, Scala ✓ ✓ ✗ Amazon CodeWhisperer Python, JavaScript, TypeScript, Java, C#, C++, Go, Ruby, PHP ✓ ✓ ✗ Codeium Python, JavaScript, TypeScript, Java, C#, C...

Top React UI Libraries ๐ŸŒŸ

๐ŸŒŸ The Ultimate Roundup of Top React UI Libraries for Your Next Project! ๐Ÿš€๐ŸŽจ Hey there, React wizards! ๐Ÿช„✨ Ready to take your frontend game to the next level? Let's dive into an even broader spectrum of incredible React UI libraries that'll make your interfaces shine like never before! ๐Ÿ’ป๐ŸŒˆ 1. Tremor UI ๐ŸŒŠ ๐ŸŒŸ Tremor UI is a rising star in the React UI galaxy! ✨ It offers a sleek and modern design language, perfect for crafting stylish buttons and more. ๐Ÿ”˜๐ŸŽจ With Tremor, you can effortlessly create eye-catching user interfaces with its intuitive API and customizable components. ๐Ÿช„✨ Key Features : Modern Design Aesthetic Easy Customization Focus on User Experience 2. Radix UI ๐ŸŒฑ ๐ŸŒŸ Radix UI is all about building accessible, powerful components for React. ๐Ÿ› ️๐Ÿ”ฉ From modals to tooltips, Radix UI provides a solid foundation for creating interactive and user-friendly interfaces. ๐ŸŒ๐Ÿงก Dive into Radix ...

Random Posts