10 JavaScript One-liners You Have Got to Add Your Arsenal as a Developer

Step Up your JavaScript game in just a couple of minutes

Twan Mulder
Nov 30, 2020 · 5 min read

1. Capitalize the first letter of a string

JavaScript function that capitalizes the first letter of a sentence.
JavaScript function that capitalizes the first letter of a sentence.
// Capitalize the first letter of a string
const capitalize = str => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
capitalize("hello, you are a cool person!");
// Result: "Hello, you are a cool person!"

2. Calculate the number of days between two dates

JavaScript function that calculates the number of days between 2 dates
JavaScript function that calculates the number of days between 2 dates
// Calculate the number of days between two dates
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
diffDays(new Date('2014-12-19'), new Date('2020-01-01'));
// Result: 1839

3. Convert a string to a number

JavaScript function that converts a string containing a number to an actual number
JavaScript function that converts a string containing a number to an actual number
// Convert a string to a number implicitly
toNumber = str => +str;
// Convert a string to a number explicitly
toNumber = str => Number(str);
toNumber("2");
// Result: 2

4. Check if an array contains any items

JavaScript function that checks if an array is empty
JavaScript function that checks if an array is empty
// Check if an array contains any items
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);
// Result: true
isNotEmpty([]);
// Result: false

5. Different ways of merging multiple arrays

A couple of different ways of merge multiple arrays using JavaScript
A couple of different ways of merge multiple arrays using JavaScript
// Different ways of merging multiple arrays// Merge but don't remove the duplications
const merge = (a, b) => a.concat(b);
// Or
const merge = (a, b) => [...a, ...b];
// Merge and remove the duplications
const merge = [...new Set(a.concat(b))];
// Or
const merge = [...new Set([...a, ...b])];

6. Sort an array containing numbers

JavaScript function that sorts an array containing numbers
JavaScript function that sorts an array containing numbers
// Sort an array containing numbers
const sort = arr => arr.sort((a, b) => a - b);
sort([1, 5, 2, 4, 3]);
// Result: [1, 2, 3, 4, 5]

7. Generate a random HEX color

JavaScript function that generates a random HEX color
JavaScript function that generates a random HEX color
// Generate a random HEX color
randomColor = () => `#${Math.random().toString(16).slice(2, 8).padStart(6, '0')}`;
// Or
const randomColor = () => `#${(~~(Math.random()*(1<<24))).toString(16)}`;

8. Get the value of a specified cookie

JavaScript function that reads the value of a specific cookie
JavaScript function that reads the value of a specific cookie
// Get the value of a specified cookie
cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
cookie('_ga');
// Result: "GA1.2.1929736587.1601974046"

9. Swap the values of 2 variables

Using JavaScript, swap the values of 2 variables around
Using JavaScript, swap the values of 2 variables around
// Swap the values of 2 variables
let a = 1;
let b = 2;
[a, b] = [b, a];
// Result:
// a = 2
// b = 1

10. Get the text that the user has selected

JavaScript function that gets the text that the user has currently selected
JavaScript function that gets the text that the user has currently selected
// Get the text that the user has selected
const getSelectedText = () => window.getSelection().toString();
getSelectedText();

DailyJS

JavaScript news and opinion.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store