
Build 10x products in minutes by chatting with AI - beyond just a prototype.
What are JavaScript one-liners?
What are the benefits of using JavaScript one-liners?
Are JavaScript one-liners always the best approach?
How can you code less and achieve more?
There can be multiple ways, but here we are going to cover the unique way that most developers love to use.
**“JavaScript One-Liner!”**🤘
JavaScript is a wonderful language that lets you do amazing things from developing frontend to backend and handling complex APIs. But beyond that, it also facilitates creating awesome stuff just using a single line of code.🥰
Don’t you think it's always cool to learn new things?
So get familiar with the 21 JavaScript OneLiners to boost up your JS app development productivity.
Let's get started! 🚀
The easiest way to check variables in an array.
const isArray = (arr) => Array.isArray(arr); console.log(isArray([1, 2, 3])); // true
console.log(isArray({ name: 'Sara' })); // false console.log(isArray('Hello World')); // false

When you want to create a temporary unique id for authentication or anything else, here is how you can make it.
const randomString = () => Math.random().toString(36).slice(2); console.log(randomString()); // could be anything!!!

You can use the code in the snippet to capitalize input.
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1); console.log(capitalize('follow for more')); // Follow For More

To calculate the number of days between two dates, find the absolute between two dates and then divide it by 86400000 (milliseconds in a single day) at the end of the day we will round the result and return the output.
const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000); console.log(daysDiff(new Date('2022-05-10'), new Date('2022-11-25'))); // 199

Shuffling two arrays using sort and random methods.
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random()); console.log(shuffleArray([1, 2, 3, 4])); // Result: [ 1, 4, 3, 2 ]
To reverse a string you can use the split, reverse and join method.
const reverse = str => str.split('').reverse().join(''); reverse('Hello World'); // Result: 'dlroW olleH'
You can merge an array using the “concat” method, the spread [“...”]operator and finally, we can use the Set object to remove any duplicate.
// Merge but don't remove the duplicates const merge = (a, b) => a.concat(b); // Or const merge = (a, b) => [...a, ...b]; // Merge and remove the duplicates const merge = [...new Set(a.concat(b))]; // Or const merge = [...new Set([...a, ...b])];
What if you want to truncate the string from the Middle?
The function will take the string as the first parameter, length as the second, and start and end as the third and fourth parameters.
It's super easy to truncate strings.
In asynchronous programming, if you want to wait for a certain amount of time, here is the way you can do that.
Convert your String to URL using Regular expression that will remove the special characters and add “-” in between the words.
Nowadays every website uses cookies. You can get the value of a specific cookie that you want to know using the following function.
Filtering Even Numbers: Creates a new array containing only even numbers from the input array.
Summing Array Elements: Calculates the total sum of all numbers in an array.
Determines the largest number within an array.
Checking if an Object is Empty: Verifies if an object has any properties.
Merging Objects: Combines two objects into a new object, with properties from the second object overriding those with the same key in the first object.
Reversing a String: Inverts the order of characters in a string.
Capitalizes the first letter of each word in a string.
Clamping a Number: Limits a number to a specified range.
Random Integer: Generates a random integer between a specified minimum and maximum value.
Debouncing a Function: Delays the execution of a function until a specified time has elapsed since the last call. Note: This is a bit more complex than a simple one-liner.
Determines if two strings are anagrams of each other (contain the same characters in different orders).
Converts a nested array into a single-level array.
There is no doubt JavaScript OneLine improves developers' productivity, but as we know it's not the only way to achieve it.
Let's find out how we can help you to improve your full-stack JavaScript app development efficiency with the revolutionary app development platform.
Whether you are a frontend or backend JavaScript developer DhiWise offers you everything to make your app development a breeze.
Here are some of the functionalities of DhiWise that you must look into.
If you still need to be assured about DhiWise's capabilities, just try it , we have ensured that you will always find it super easy and fast to code.
So enjoy coding!
That's all, I hope you enjoyed the article. Now you know about the 21 javaScript OneLiner + functionalities of DhiWise. Don’t forget to check out our other medium articles here .
Have a nice day!
const truncateStringMiddle = (string, length, start, end) => {
return `${string.slice(0, start)}...${string.slice(string.length - end)}`;
};
console.log(
truncateStringMiddle(
'A long story goes here but then eventually ends!', // string
25, // total size needed
13, // chars to keep from start
17, // chars to keep from end
),
); // A long story ... eventually ends!
const truncateString = (string, length) => {
return string.length < length ? string : `${string.slice(0, length - 3)}...`;
};
console.log(truncateString('Truncate the string because, its too long', 30));
// Truncate the string because...
const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
const test = async () => {await wait(1000)
console.log("waited for 1 second.")
}
test()
// the output will be generated after 1000 milliseconds.
const slugify = string => string.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]+/g, ''); // Example
console.log(slugify('Lifesaving JavaScript OneLiners'));
// Result:lifesaving-javascript-oneliners
const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
console.log(cookie('_ga')); // Result: GA1.1.1556710793.1646367473
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6]const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 15const numbers = [10, 5, 8, 20, 3];
const max = Math.max(...numbers);
console.log(max); // Output: 20const emptyObj = {};
const nonEmptyObj = { name: "Alice" };
const isEmptyObject = obj => Object.keys(obj).length === 0;
console.log(isEmptyObject(emptyObj)); // Output: true
console.log(isEmptyObject(nonEmptyObj)); // Output: falseconst obj1 = { name: "Alice", age: 25 };
const obj2 = { city: "New York" };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // Output: { name: 'Alice', age: 25, city: 'New York' }const str = "hello";
const reversedStr = str.split('').reverse().join('');
console.log(reversedStr); // Output: "olleh"const str = "hello world";
const titleCaseStr = str.split(' ').map(word => word[0].toUpperCase() + word.slice(1)).join(' ');
console.log(titleCaseStr); // Output: "Hello World"const clamp = (num, min, max) => Math.min(Math.max(num, min), max);
console.log(clamp(10, 5, 15)); // Output: 10
console.log(clamp(2, 5, 15)); // Output: 5const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
console.log(randomInt(1, 10)); // Output: A random number between 1 and 10const debounce = (func, wait) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => func(...args), wait);
};
};const isAnagram = (str1, str2) => str1.split('').sort().join('') === str2.split('').sort().join('');
console.log(isAnagram("listen", "silent")); // Output: trueconst nestedArray = [1, [2, 3], 4, [5, [6]]];
const flattenedArray = nestedArray.flat(Infinity);
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6]