# 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

Nov 30, 2020 · 5 min read

## 1. Capitalize the first letter of a string

`// Capitalize the first letter of a stringconst 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

`// Calculate the number of days between two datesconst 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

`// Convert a string to a number implicitlytoNumber = str => +str;// Convert a string to a number explicitlytoNumber = str => Number(str);toNumber("2");// Result: 2`

## 4. Check if an array contains any items

`// Check if an array contains any itemsconst isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;isNotEmpty([1, 2, 3]);// Result: trueisNotEmpty([]);// Result: false`

## 5. Different ways of merging multiple arrays

`// Different ways of merging multiple arrays// Merge but don't remove the duplicationsconst merge = (a, b) => a.concat(b);// Orconst merge = (a, b) => [...a, ...b];// Merge and remove the duplicationsconst merge = [...new Set(a.concat(b))];// Orconst merge = [...new Set([...a, ...b])];`

## 6. Sort an array containing numbers

`// Sort an array containing numbersconst 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

`// Generate a random HEX colorrandomColor = () => `#\${Math.random().toString(16).slice(2, 8).padStart(6, '0')}`;// Orconst randomColor = () => `#\${(~~(Math.random()*(1<<24))).toString(16)}`;`

## 8. Get the value of a specified cookie

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

## 9. Swap the values of 2 variables

`// Swap the values of 2 variableslet a = 1;let b = 2;[a, b] = [b, a];// Result: // a = 2// b = 1`

## 10. Get the text that the user has selected

`// Get the text that the user has selectedconst getSelectedText = () => window.getSelection().toString();getSelectedText();`

Written by

Written by