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

2. Checking if a Variable is Null:

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

3. Checking if a Variable is Empty:

const isEmpty = variable => !variable;
JavaScript

4. Checking if a Variable is an Array:

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

5. Checking if a Variable is an Object:

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

6. Checking if a Variable is a Function:

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

7. Getting the Last Element of an Array:

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

8. Flattening an Array:

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

9. Reversing a String:

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

10. Generating a Random Number:

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

11. Removing Duplicates from an Array:

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

12. Checking if an Array Contains a Specific Value:

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

13. Checking if a String Contains a Substring:

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

14. Getting the Current Date and Time:

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

15. Checking if a Year is a Leap Year:

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

16. Truncating a Number to a Specified Decimal Place:

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

17. Checking if an Object has a Specific Property:

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

18. Converting a String to Title Case:

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

19. Repeating a String N Times:

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

20. Generating a Range of Numbers:

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

21. Summing Numbers in an Array:

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

22. Getting the Maximum Value in an Array:

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

23. Getting the Minimum Value in an Array:

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

24. Checking if a Number is Even:

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

25. Checking if a Number is Odd:

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

26. Checking if a String is Palindrome:

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

27. Reversing the Order of Words in a String:

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

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

29. Converting Fahrenheit to Celsius:

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

30. Converting Celsius to Fahrenheit:

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

31. Factorial of a Number:

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

32. Fibonacci Sequence:

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

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

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

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

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

34. Shuffle an Array:

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

35. Checking if a Number is a Perfect Square:

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

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

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

37. Checking if a Number is a Palindrome:

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

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

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

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

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

41. Converting a Number to Binary:

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

42. Converting a Binary Number to Decimal:

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

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

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

44. Converting an Object to Query Parameters String:

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

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

46. Reversing an Array in Place:

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

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

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

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

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

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

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

50. Finding the Longest Word in a Sentence:

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

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 Get Free Unlimited Bandwidth and Storage Using jsDelivr and GitHub

How to Get Free Unlimited Bandwidth and Storage Using jsDelivr and GitHub Are you tired of paying for expensive content delivery networks (CDNs) and storage solutions for your web projects? Look no further! In this guide, we'll show you how to leverage jsDelivr and GitHub to get free unlimited bandwidth and storage. Whether you're a seasoned developer or just getting started, this solution will save you money and improve the performance of your web projects. What is jsDelivr? jsDelivr is a free, fast, and reliable CDN for open-source files. It provides a convenient way to serve your static assets (like JavaScript, CSS, images, and more) with the benefits of a global CDN, including faster load times and unlimited bandwidth. What is GitHub? GitHub is a popular platform for version control and collaboration. It allows you to host your code repositories and manage your projects with ease. By combining GitHub with jsD...

Best VS Code extensions for developers in 2024

Here are some of the best VS Code extensions for developers in 2024, including a range of productivity tools, debuggers, and visual enhancements to streamline your coding workflow. Additionally, you'll find some popular themes to customize your editor's appearance. Top VS Code Extensions for Developers in 2024 Shade Theme by SH20RAJ Enhance your code readability with this well-designed theme, perfect for long coding sessions. Shade Theme Prettier A widely used code formatter that ensures your code is styled consistently across your projects. Prettier GitLens Provides rich visualizations and insights into your Git repository, helping you understand code changes and history. GitLens Auto Rename Tag Automatically renames paired HTML/XML tags, reducing errors and saving time. Auto Rename Tag Bracket Pair Colorizer Colors matching brackets to improve code readability, especially useful for complex nested structures. Bracket Pair Colorizer CSS Peek...

Top 50 Useful Regex Patterns

Title: Mastering Regular Expressions in JavaScript: Top 50 Useful Regex Patterns Introduction: Regular expressions (regex) are a powerful tool for pattern matching and text manipulation in JavaScript. Whether you're validating user input, extracting data from strings, or replacing text, regex can streamline your coding tasks. In this article, we'll explore 50 useful regex patterns that every JavaScript developer should know. These regex patterns cover a wide range of common scenarios, from validating email addresses to parsing URLs and beyond. 1. Validating Email Addresses: const emailRegex = /^[ \w -]+( \. [ \w -]+)*@([ \w -]+ \. )+[a-zA-Z]{2,7}$/; 2. Validating URLs: const urlRegex = /^(https?: \/ \/ )?([ \d a-z.-]+) \. ([a-z.]{2,6})([/ \w .-]*)* \/ ?$/; 3. Validating Dates in YYYY-MM-DD Format: const dateRegex = /^ \ d {4} - \ d {2} - \ d {2} $/; 4. Validating Phone Numbers (US Format): const phoneRegex = /^ \ ( ?( \ d {3} ) \ ) ?[- ]?( \ d {3} )[- ]?( \ d {4} )...

Random Posts