Master JavaScript with These 8 One-Liners for Pro

Umar Farooque Khan
3 min readApr 3, 2024

Let’s dive into some powerful JavaScript one-liners that can help you optimize your code and make it more efficient. These concise solutions cover common tasks, making your development process faster and more enjoyable

1. Generate a random Number

Generating a random number in JavaScript can be achieved using the Math.random() function. This function returns a floating-point number between 0 (inclusive) and 1 (exclusive). To generate random numbers within a specific range, you can manipulate the result using mathematical operations.

// Generating a random number between min and max
const getRandomInteger = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
console.log(getRandomInteger(1, 100)) //13
console.log(getRandomInteger(1, 100))//6
console.log(getRandomInteger(1, 100))//98

2. Check if a number is even or odd

It employs the modulo operator to assess divisibility by two, returning “Even” if divisible and “Odd” otherwise. The function offers a clear and concise means of categorizing numeric values, aiding in various programming tasks and logic operations.

// Short arrow function to check if a number is even or odd
const checkEvenOrOdd = number => number % 2 === 0 ? "Even" : "Odd";
// Three outputs for different numbers
console.log(checkEvenOrOdd(4)); // Output: Even
console.log(checkEvenOrOdd(7)); // Output: Odd
console.log(checkEvenOrOdd(0)); // Output: Even

3. Generate a random Alpha numeric string

This arrow function generates a random alphanumeric string of a specified length by creating an array of the desired length and filling it with random alphanumeric characters. It then concatenates these characters into a single string.

// Function to generate a random alphanumeric string of a specified length
const generateRandomString = length => Array.from({ length }, () => Math.random().toString(36).charAt(2)).join('')
// Call the function three times and print the generated strings
console.log(generateRandomString(8)); // Example output: "8ahx9f3c"
console.log(generateRandomString(8)); // Example output: "7b3dfg9z"
console.log(generateRandomString(8)); // Example output: "lkh2f9ad"

4. Convert a string to camelCase

This arrow function converts a creative string into camelCase format while preserving spaces between words.

// Arrow function to convert a creative string to camelCase while keeping spaces intact
const toCamelCase = str => str.replace(/\s(.)/g, ($1) => $1.toUpperCase()).replace(/\s/g, '').replace(/^(.)/, ($1) => $1.toLowerCase());
// Call the function three times with creatively crafted strings and print the output
console.log(toCamelCase("the quick brown fox jumps")); // Output: theQuickBrownFoxJumps
console.log(toCamelCase("this is a beautifully crafted sentence")); // Output: thisIsABeautifullyCraftedSentence
console.log(toCamelCase("ok goole")); // Output: okGoole

5. Sum of array elements

To calculates the sum of all elements in an array. It utilizes the reduce method to iterate over the array, accumulating the sum, and starts with an initial value of 0.

const sum = (array) => array.reduce((acc, curr) => acc + curr, 0);
// Example usage:
console.log(sum([1, 2, 3])); // Output: 6
console.log(sum([-1, 5, 10])); // Output: 14
console.log(sum([0, 0, 0])); // Output: 0

6. Find the Difference in Days Between Two Dates

You can calculate the difference in days between two dates by converting both dates to milliseconds since the Unix epoch, then subtracting one from the other.

// Short arrow function to calculate the difference in days between two dates
const differenceInDays = (date1, date2) => Math.ceil(Math.abs((date2 - date1) / (1000 * 60 * 60 * 24)))
// Example usage:
const date1 = new Date('2024-03-15');
const date2 = new Date('2024-04-02');
console.log(differenceInDays(date1, date2)); // Output: 18

const date3 = new Date('2023-11-11');
const date4 = new Date('2024-01-01');
console.log(differenceInDays(date3, date4)); // Output: 51

const date5 = new Date('2024-05-05');
const date6 = new Date('2024-06-06');
console.log(differenceInDays(date5, date6)); // Output: 32

7. Title Case Strings

It converts the first character to uppercase using toUpperCase() and then concatenates it with the rest of the string using slice(1).

const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
// Example usage:
console.log(capitalize('hello')); // Output: 'Hello'
console.log(capitalize('javascript')); // Output: 'Javascript'
console.log(capitalize('openai')); // Output: 'Openai'

8. Truncate: Keep Strings Concise

This one-liner truncates a string to a specified maximum length and appends ‘…’ if the string exceeds the limit, maintaining the original string’s length otherwise.

const truncate = (str, maxLength) => str.length > maxLength ? str.slice(0, maxLength) + '...' : str;
// Example usage:
console.log(truncate('Lorem ipsum dolor sit amet', 10)); // Output: 'Lorem ipsu...'
console.log(truncate('This is a long sentence', 15)); // Output: 'This is a long...'
console.log(truncate('Short', 10)); // Output: 'Short'

Here are some additional high-quality tutorials for you to explore:

  1. JavaScript interview Question and Answer
  2. Node Js Interview Question and Answer
  3. JavaScript Tricky Question
  4. JavaScript Array Interview Questions

--

--

Umar Farooque Khan

Experienced software developer with a passion for clean code and problem-solving. Full-stack expertise in web development. Lifelong learner and team player.