DEV Community

James saloman
James saloman

Posted on

Killer JavaScript One-Liners: Code That Packs a Punch!

Introduction

JavaScript is a versatile and expressive language known for its simplicity and elegance. In this blog post, we're diving into the world of JavaScript one-liners - compact lines of code that achieve incredible results. These one-liners are not just clever; they demonstrate the power and flexibility of JavaScript. Whether you're a beginner or an experienced developer, you'll appreciate the magic of concise code. Let's explore some killer JavaScript one-liners!

A Few Ground Rules

Before we dive into the one-liners, let's establish some ground rules:

1. Readability Matters: While concise code is cool, it shouldn't come at the expense of readability. Clever one-liners should enhance, not hinder, code comprehension.

2. Know Your Audience: One-liners can be great for personal experimentation, but they may not always be suitable for team projects. Ensure your team understands and appreciates concise code.

3. Use Cases Matter: Not every problem is best solved with a one-liner. Evaluate the problem, its complexity, and the context before choosing a concise solution.

1. Hello, World!

console.log('Hello, World!');
Enter fullscreen mode Exit fullscreen mode

This classic "Hello, World!" example demonstrates how JavaScript's console.log() can output text to the console in a single line. Simplicity is key.

2. Reversing a String

const reversedString = 'Hello, World!'.split('').reverse().join('');
Enter fullscreen mode Exit fullscreen mode

In just one line, we split a string into an array of characters, reverse the array, and join it back into a string, effectively reversing the original string.

3. Checking for Palindromes

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

This one-liner defines a function that checks whether a string is a palindrome, a word or phrase that reads the same forwards and backward.

4. Summing Numbers in an Array

const sum = arr => arr.reduce((total, num) => total + num, 0);
Enter fullscreen mode Exit fullscreen mode

In this line, we use the reduce method to add up all the numbers in an array, starting with an initial value of 0.

5. Generating a Random Number

const randomNumber = Math.random();
Enter fullscreen mode Exit fullscreen mode

This one-liner generates a random number between 0 and 1, thanks to JavaScript's built-in Math.random() function.

6. Checking for Prime Numbers

const isPrime = num => num > 1 && ![...Array(num).keys()].slice(2).some(i => num % i === 0);
Enter fullscreen mode Exit fullscreen mode

In this compact code, we determine whether a number is prime by checking if it's greater than 1 and doesn't have divisors other than 1 and itself.

7. Swapping Variables

let a = 5, b = 10;
[a, b] = [b, a];
Enter fullscreen mode Exit fullscreen mode

With this one-liner, we swap the values of two variables a and b without needing a temporary variable.

8. Finding the Maximum Value in an Array

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

The spread operator (...) in this one-liner allows us to find the maximum value in an array with ease.

9. Ternary Operators

const isEven = num => num % 2 === 0 ? 'Even' : 'Odd';
Enter fullscreen mode Exit fullscreen mode

Ternary operators like this one-liner are a concise way to express conditional logic.

10. FizzBuzz

for(let i = 1; i <= 100; i++) console.log(i % 15 === 0 ? 'FizzBuzz' : i % 3 === 0 ? 'Fizz' : i % 5 === 0 ? 'Buzz' : i);
Enter fullscreen mode Exit fullscreen mode

This one-liner is a compact FizzBuzz solution, printing "Fizz" for multiples of 3, "Buzz" for multiples of 5, and "FizzBuzz" for multiples of both.

Conclusion

JavaScript one-liners showcase the language's beauty and versatility. They provide elegant solutions to everyday coding challenges, making complex tasks seem simple. By understanding and using these one-liners, you can become a more efficient and expressive JavaScript developer. So, experiment, practice, and embrace the power of compact code in your projects. Happy coding!

Top comments (4)

Collapse
 
cheuksing profile image
Tommy Chan

"Whether you're a beginner or an experienced developer, you'll appreciate the magic of concise code."

I don't get it. Nothing can beat readability. One liner are usually hard to read, unless its super simple. And in some case its shorter to be multiline after minified. I do appreciate elegant code that solve a complex problem in a efficient way with very few code tho. For example, I remember someone can find sqrt with Babylonian Algorithm with a very good initial guess in a few lines.

Collapse
 
frankwisniewski profile image
Frank Wisniewski
  • 'Hello πŸ‘ͺ World!'.split('').reverse().join('');` --> fail
  • isPalindrome('uπŸ‘ͺu') --> fail
  • isPrime(999999999989) --> fail
Collapse
 
saloman_james profile image
James saloman

Thanks for letting me know, Hereafter I do more research before I post.

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

Checking for palindromes:

const isPalindrome = ([...s]) => ''+s == s.reverse()
Enter fullscreen mode Exit fullscreen mode