10 JavaScript One-Liners for Beginner Developers to Look Pro

Rehan Pinjari
6 min readJun 9, 2024
10 JavaScript One-Liners for Beginner Developers to Look Pro

Have you ever been elbow-deep in coding when someone else steps in and solves a problem with a single line of JavaScript? It’s like a coding magic trick.

This is the power of one-liners. These short code snippets can be highly effective, making you feel like a JavaScript Pro.

But, before you start getting one-liners into every line of code, let’s break it down.

One-liners are short snippets of JavaScript code that compress functionality onto a single line.

They can help you write more compact code and occasionally even improve readability.

What are the benefits? You save time, create cleaner code, and maybe even impress the other developers (just a little).

We’re now focusing on practical, beginner-friendly one-liners that will get you a quick win.

Here are some great options to add to your JavaScript toolbox:

Have a BIG IDEA in mind? Let’s discuss what we can gain together.

Write at Gmail | LinkedIn

1. Array Filtering

Suppose you have an array of test scores and need to find all of the A’s (in this case, even numbers). One-liners to the help!

const scores = [85, 92, 73, 98, 80];
const evenScores = scores.filter(num => num % 2 === 0);

// evenScores will be [92, 98, 80]

This code uses the filter method to create a new array containing only the elements that pass a test.

The arrow function (num => num % 2 === 0) checks if each number is even.

When to use: Filtering removing unwanted elements from arrays is a common operation. This one-liner is valuable for keeping your data clean.

2. Array Mapping

If you have an array of side lengths and want to figure out the area of each square. This one-liner can map (convert) each element in the array into its square:

const sideLengths = [5, 3, 7];
const areas = sideLengths.map(num => num * num);

// areas will be [25, 9, 49]

The map method creates a new array with the results of calling a provided function on every element in the original array.

Here, the function squares each number.

When to use: This one-liner is useful for performing mathematical operations on each element in an array.

3. Flattening Arrays

Sometimes you come across nested arrays, such as a list of grocery store products with sub-items for each variant. One-liners can help you flatten these structures:

const nestedGroceries = [
["Apples", ["Red", "Green"]],
["Milk", ["Whole", "2%"]]
];
const flatGroceries = nestedGroceries.flat();

// flatGroceries will be ["Apples", "Red", "Green", "Milk", "Whole", "2%"]

The flat method (available in ES6 and later) creates a new array with all sub-array elements concatenated into it.

This can simplify your data manipulation tasks.

When to use: Flattening nested arrays makes it easier to work with the data in a single dimension.

4. Unique Elements (No Duplicates Allowed!)

Maybe you have a guest list that has some unfortunate duplicate entries.

One-liners help you ensure that everyone gets a unique invitation (avoiding awkward “wait, I got two?” situations).

// Original guest list with a duplicate entry
const guestList = ["Alice", "Bob", "Charlie", "Alice"];

// Remove duplicates by converting the array to a Set and back to an array
const uniqueGuestList = [...new Set(guestList)];

// uniqueGuestList will be ["Alice", "Bob", "Charlie"]
console.log(uniqueGuestList);

This one-liner uses the magic of Sets. Sets store unique values.

We spread (...) the elements from a Set containing the unique guests from the original list back into a new array.

When to use: Data cleaning often means the removal of duplicates from arrays. This one-liner keeps your data clean and neat.

5. Shorthand Conditionals

Ever written an if...else statement that spans multiple lines, just to assign a value based on a condition? There's a more concise way:

// Define the age of the user
const age = 18;

// Determine the message based on the user's age
const message = age >= 18 ? "Welcome!" : "Sorry, not yet.";

// Output the message
console.log(message);

This code uses the ternary operator, a fancy way of writing a short-hand if-else statement in a single line.

The condition (age >= 18) is checked, and the corresponding value ("Welcome!" or "Sorry, not yet.") is assigned to the message variable.

When to use: Shorthand conditionals are great for performing simple assignments based on situations while keeping your code clean and efficient.

Readability Consideration: While ternary operators are nice, complex situations may make code hard to understand. Use them wisely!

6. String Reversal

One-liners can even be used with text! How about reversing a string to see if it’s a palindrome (a word that reads the same backward and forward, such as “racecar”)?

const str = "Hello, world!";
const reversedStr = str.split('').reverse().join('');

// reversedStr will be "!dlrow ,olleH"

This one-liner breaks the string into an array of characters, reverses the order of the elements, and then rejoins them into a new string — all in one line!

When to use: String manipulation tasks such as reversing or extracting substrings can be simplified with one-liners.

Remember: Complex string operations might be better suited to lengthier, longer code for readability.

7. Object Property Existence

Imagine that you’re creating a user profile system and need to figure out whether a specific attribute (such as “email”) exists in a user object. This one-liner might be helpful:

const user = { name: "Alice", age: 30 };

// Check if the user object has an 'email' property
const hasEmail = "email" in user;

// hasEmail will be false because the 'email' property is not present in the user object

The in operator checks if a property exists within an object. Here, we check if the "email" property exists in the user object.

When to use: Validating data based on the availability of specified attributes in objects is an everyday situation. This one-liner offers a straightforward solution.

8. Default Parameter Values

How about creating an operation to greet users but giving a backup value in case no name is provided? One-liners can manage this:

const greet = (name = "Guest") => `Hello, ${name}!`;
console.log(greet());

// Output: Hello, Guest!

console.log(greet("Bob"));
// Output: Hello, Bob!

This one-liner uses ES6 default parameters. Here, if no name is provided when calling the greet function, the default value of "Guest" is used.

When to use: Default parameters avoid errors when functions are called without the proper arguments, making your code stronger.

9. Compact Arrays

Sometimes you might encounter arrays with empty values or null elements. One-liners can help you remove these unwanted guests:

const numbers = [1, 0, null, 3]; // Original array
const compactNumbers = numbers.filter(Boolean); // Using filter with Boolean as the callback function

// compactNumbers will be [1, 3] because Boolean(1) is true, Boolean(0) is false, Boolean(null) is false, and Boolean(3) is true

This one-liner utilizes the filter method again. However, this time, the filter checks for "falsy" values (like null, undefined, 0, "", and NaN) using the Boolean constructor.

Any element that evaluates to false is excluded from the new array.

When to use: Cleaning up arrays to remove unnecessary elements guarantees that you are dealing with data that is important.

10. Dynamic Object Keys

One-liners can even be used to build objects with keys that are determined after operation. Mind blown?

const prop = "score";
const person = { [prop]: 90 };

// person will be {score: 90}

This one-liner uses computed property names. The value of the prop variable is used as the key name within the curly braces when creating the object.

This allows for dynamic key creation based on variables or expressions.

When to use: Dynamic object keys are useful for creating things whose structures are not preset.

Remember: While impressive, advanced one-liners for dynamic key generation can affect reading. Use them wisely!

Final Words

I hope you’ve learned some great one-liners to improve your JavaScript code.

Remember that one-liners are strong tools, but they must be used carefully to guarantee code clarity and maintainability.

Keep an eye out for future posts as we’ll go further into JavaScript concepts and go on new coding adventures!

If you enjoyed this, consider buying me a coffee! ☕️

--

--