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.
1 const isArray = (arr) => Array.isArray(arr); 2 console.log(isArray([1, 2, 3])); 3 // true 4
1 console.log(isArray({ name: 'Sara' })); 2 // false 3 console.log(isArray('Hello World')); 4 // false 5
When you want to create a temporary unique id for authentication or anything else, here is how you can make it.
1 const randomString = () => Math.random().toString(36).slice(2); 2 console.log(randomString()); // could be anything!!!
You can use the code in the snippet to capitalize input.
1 const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1); 2 console.log(capitalize('follow for more')); // Follow For More 3
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.
1 const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000); 2 console.log(daysDiff(new Date('2022-05-10'), new Date('2022-11-25'))); // 199
Shuffling two arrays using sort and random methods.
1 const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random()); 2 3 console.log(shuffleArray([1, 2, 3, 4])); // Result: [ 1, 4, 3, 2 ] 4
To reverse a string you can use the split, reverse and join method.
1 const reverse = str => str.split('').reverse().join(''); 2 3 reverse('Hello World'); // Result: 'dlroW olleH' 4
You can merge an array using the “concat” method, the spread [“...”]operator and finally, we can use the Set object to remove any duplicate.
1 // Merge but don't remove the duplicates 2 const merge = (a, b) => a.concat(b); 3 // Or 4 const merge = (a, b) => [...a, ...b]; 5 // Merge and remove the duplicates 6 const merge = [...new Set(a.concat(b))]; 7 // Or 8 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.
1 const truncateStringMiddle = (string, length, start, end) => { 2 return `${string.slice(0, start)}...${string.slice(string.length - end)}`; 3 }; 4
1 console.log( 2 truncateStringMiddle( 3 'A long story goes here but then eventually ends!', // string 4 25, // total size needed 5 13, // chars to keep from start 6 17, // chars to keep from end 7 ), 8 ); // A long story ... eventually ends! 9
It's super easy to truncate strings.
1 const truncateString = (string, length) => { 2 return string.length < length ? string : `${string.slice(0, length - 3)}...`; 3 }; 4 console.log(truncateString('Truncate the string because, its too long', 30)); 5 // Truncate the string because... 6
In asynchronous programming, if you want to wait for a certain amount of time, here is the way you can do that.
1 const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); 2 const test = async () => {await wait(1000) 3 console.log("waited for 1 second.") 4 } 5 test() 6 // the output will be generated after 1000 milliseconds. 7
Convert your String to URL using Regular expression that will remove the special characters and add “-” in between the words.
1 const slugify = string => string.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]+/g, ''); // Example 2 console.log(slugify('Lifesaving JavaScript OneLiners')); 3 // Result:lifesaving-javascript-oneliners 4
Nowadays every website uses cookies. You can get the value of a specific cookie that you want to know using the following function.
1 const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift(); 2 console.log(cookie('_ga')); // Result: GA1.1.1556710793.1646367473 3
Filtering Even Numbers: Creates a new array containing only even numbers from the input array.
1const numbers = [1, 2, 3, 4, 5, 6]; 2const evenNumbers = numbers.filter(num => num % 2 === 0); 3console.log(evenNumbers); // Output: [2, 4, 6]
Summing Array Elements: Calculates the total sum of all numbers in an array.
1const numbers = [1, 2, 3, 4, 5]; 2const sum = numbers.reduce((acc, curr) => acc + curr, 0); 3console.log(sum); // Output: 15
Determines the largest number within an array.
1const numbers = [10, 5, 8, 20, 3]; 2const max = Math.max(...numbers); 3console.log(max); // Output: 20
Checking if an Object is Empty: Verifies if an object has any properties.
1const emptyObj = {}; 2const nonEmptyObj = { name: "Alice" }; 3const isEmptyObject = obj => Object.keys(obj).length === 0; 4console.log(isEmptyObject(emptyObj)); // Output: true 5console.log(isEmptyObject(nonEmptyObj)); // Output: false
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.
1const obj1 = { name: "Alice", age: 25 }; 2const obj2 = { city: "New York" }; 3const mergedObj = { ...obj1, ...obj2 }; 4console.log(mergedObj); // Output: { name: 'Alice', age: 25, city: 'New York' }
Reversing a String: Inverts the order of characters in a string.
1const str = "hello"; 2const reversedStr = str.split('').reverse().join(''); 3console.log(reversedStr); // Output: "olleh"
Capitalizes the first letter of each word in a string.
1const str = "hello world"; 2const titleCaseStr = str.split(' ').map(word => word[0].toUpperCase() + word.slice(1)).join(' '); 3console.log(titleCaseStr); // Output: "Hello World"
Clamping a Number: Limits a number to a specified range.
1const clamp = (num, min, max) => Math.min(Math.max(num, min), max); 2console.log(clamp(10, 5, 15)); // Output: 10 3console.log(clamp(2, 5, 15)); // Output: 5
Random Integer: Generates a random integer between a specified minimum and maximum value.
1const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; 2console.log(randomInt(1, 10)); // Output: A random number between 1 and 10
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.
1const debounce = (func, wait) => { 2 let timeout; 3 return (...args) => { 4 clearTimeout(timeout); 5 timeout = setTimeout(() => func(...args), wait); 6 }; 7};
Determines if two strings are anagrams of each other (contain the same characters in different orders).
1const isAnagram = (str1, str2) => str1.split('').sort().join('') === str2.split('').sort().join(''); 2console.log(isAnagram("listen", "silent")); // Output: true
Converts a nested array into a single-level array.
1const nestedArray = [1, [2, 3], 4, [5, [6]]]; 2const flattenedArray = nestedArray.flat(Infinity); 3console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6]
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!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.