JavaScript One-Liners to Use in Every Project
Hi, in javascript one-liner refers to concise code snippets that can be written in a single line, the more you get used to it , more easy it becomes
Get Hemanth KV’s stories in your inbox
Join Medium for free to get updates from this writer.
|| Follow ME
These one-liners are often used for simplicity, brevity, or to accomplish a specific task quickly. Here are a few examples of common JavaScript one-liners:
//conditional assignment
let value = x || defaultValue;//ternary operation
let result = condition ? valueIfTrue : valueIfFalse;//arrow funtion
const double = x => x * 2;//Array manipulation
const numbers = [1, 2, 3];
const doubledNumbers = numbers.map(x => x * 2);//object destruction
const { name, age } = person;
//array destruction
const [first, second, third] = array;//short circuit evaluation
const result = a && b;//Template literals
const greeting = `Hello, ${name}!`;//Array filtering
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(x => x % 2 === 0);//object shorthand
const name = "John";
const age = 30;
const person = { name, age };//Array sum
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((total, num) => total + num, 0);//object mapping
const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
{ id: 3, name: "Bob" }
];
const userIdMap = users.reduce((map, user) => ({ ...map, [user.id]: user }), {});//Flatten an array
const nestedArray = [[1, 2], [3, 4], [5, 6]];
const flattenedArray = nestedArray.reduce((flat, arr) => [...flat, ...arr], []);//find maximum value
const numbers = [10, 5, 8, 2, 7];
const maxNumber = Math.max(...numbers);//Remove duplicates from an array
const numbers = [1, 2, 3, 4, 4, 5, 5];
const uniqueNumbers = [...new Set(numbers)];//group object by property
const users = [
{ id: 1, name: "John", group: "A" },
{ id: 2, name: "Jane", group: "B" },
{ id: 3, name: "Bob", group: "A" }
];
const groupedUsers = users.reduce((groups, user) => ({ ...groups, [user.group]: [...(groups[user.group] || []), user] }), {});//Genarate an array range
const start = 1;
const end = 5;
const range = Array.from({ length: end - start + 1 }, (_, index) => start + index);//swap variables
let a = 5;
let b = 10;
[a, b] = [b, a];//Capitalize first letter of each word in a sentence
const sentence = "hello world";
const capitalized = sentence.replace(/\b\w/g, match => match.toUpperCase());// just for fun , doing fabonacci sequence in one-line
const fibonacci = n => Array.from({ length: n }, (_, i) => i > 1 ? fibonacci[i - 1] + fibonacci[i - 2] : i);Remember, while one-liners can be powerful, readability and maintainability should always be prioritised when writing code.
Thank you… 😉









