Helpful JavaScript one-liners to code cleaner

JavaScript is unarguably one of the most popular programming languages in the world today. It is home to vanilla programming, multiple frameworks, complex APIs, and a wide range of libraries, modules, and functions.

Whether you are a newbie or a more experienced developer, using one-liners is a terrific way to do more things with JavaScript. This article will be looking at over 25 JavaScript one-liners that will ease your coding and make your code cleaner. They are simple, easy to remember, and show proficiency.

Let’s go!

1

Eligibility to vote

This function checks if a citizen is eligible to vote. We set the minimum age of voting to 18. We use a called ternary operator.

// To check the eligibility to vote 
let age = 25; 
let votingelig = (age >= 18) ? "You are eligible to vote." : "You are not eligible to vote yet"; 

document.write(votingelig);
2

To get the last occurrence of a value

We can get the last occurrence of a string using lastIndexOf() method to locate/search that specific value.

let lastoccurance = 'Jerusalem'.lastIndexOf('e'); 
document.write(lastoccurance);
3

Getting the domain name from an email

Here, we use substring() and IndexOf() methods to extract a substring from a string.

let getdomain = 'codecodablog@gmail.com'.substring('codecodablog@gmail.com'.indexOf('@') + 1); 
document.write(getdomain);
4

No Fives

This program aims to get the count of numbers within a specific range but will not count any number with a 5 in it. For example, the range of numbers between 4 and 16 will return 11 because 5 and 15 were omitted. The result, though, can have a five.

//Getting the count of a range of numbers but no fives 
nofives = (a, b) => Array.from(Array(b - a + 1), (b, i) => a + i).filter(b => !/5/.test(b)).length;
document.write(nofives(12,49));
5

Find the length of the shortest word

Give this program a string of text, and it will return the length of the shortest word.

//To get the length of the shortest word in the text 
const findShortestword = (s) => s.split(" ").sort((a, b) => b.length - a.length).pop().length; 
document.write(findShortestword("Bad situations cannot last"));
6

Converting Text to Camel Case without Spaces

camelCase is a text characterization where the first letter of a word is in capital letters. This program converts a string in any case into camelCase and removes the spaces within the text. Although it looks rowdy, it is straightforward.

//Program to convert text to camel case without spaces 
String.prototype.camelCase=function(){ 
  return this.trim().split(' ').map((w,e) => w.split('').map((q,r) => 
  {
    if (r==0) { 
      return q.toUpperCase()
    } 
    else
    { 
      return q.toLowerCase()
    }
  }).join('')).join('');
}
document.write("my name is Effiong".camelCase());
7

Check availability of CEO

This function checks the availability of a CEO according to his meeting schedules.

Suppose he has a text message when he is unavailable. In that case, the program should send an automated message telling the texter that the CEO is unavailable and the time he will be available. If the current time has no appointment, the output is true.

The program takes two arguments - the schedule and the current time.

// to check availability of a CEO 
const checkAvailability = (s,c) => s.reduce(((x,y) => y[0] < c && y[1] > c ? y[1] : x), true);
document.write(checkAvailability([["08:30", "1:20"], ["12:20", "15:50"]], "13:00"));
8

Trimming characters

Using the trim() method, we would like to return a string stripped of whitespace characters – we remove them from the beginning and the end of the text.

//To trim a string
let trimvalue = ' Jerusalem '.trim();
document.write(trimvalue);
9

Checking a number to see if it is positive, negative, or zero

Here, we will check if a number is positive, negative, or zero

// program to check if number is positive, negative or zero 
let d = -10; 
let result = (d >= 0) ? (d == 0 ? "zero" : "positive") : "negative"; 
document.write('Number is ${result}.');
10

Getting the square root of numbers

To get the square root of a set of numbers, we use the map() and Math() inbuilt functions.

//simple calculations to get the square root of a set of numbers 
let sqroot = [9, 36, 49].map(Math.sqrt); 
document.write(sqroot);
11

Getting a fixed decimal point

Rounding up numbers to a certain number of decimal places is a general operation in mathematics. As such, we can perform such actions using JavaScript’s Math() function.

First value: the number to be rounded up
Second value: the amount the number is to be rounded up to

//program to round up numbers to a certain decimal place 
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed); 
document.write(toFixed(88.143786364, 5));

Using the filter function

For the following two one-liners, we will be using the filter function to create a new array of elements that fall under a specific criterion from an existing array.

12

Lucky Number

Say we have a range of numbers between 1 to 12, but we only want to filter numbers less than nine because numbers equal to and lower than 9 are our lucky numbers. We can easily do this using filter() method. 

//filtering nos greater than 9
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; 
let luckynos = nums.filter(nos => nos <= 9); 
document.write(luckynos);
13

Movie characters and the movies they belong to

Filtering many numbers isn’t the only one-liner we can do with the filter() function. Filter() works with objects and properties in hash tables. After mapping values to each index, we can filter out specific values and indexes. 

let characters = [
  {movie: 'Avatar Last Airbender', character: 'Sokka'}, 
  {movie: 'Moana', character: 'Maui'}, 
  {movie: 'Avatar Last Airbender', character: 'Azula'}, 
  {movie: 'Moana', character: 'Sina'} 
]
let char= characters.filter(char => char.movie == 'Avatar Last Airbender') 
document.write(char);
14

The sum of numbers

To calculate the sum of numbers in a given array, we use the reduce() function. The reduce() function, like its name implies, reduces an array to a single value. Its return value is stored in the form of totals. 

//calculating the sum of the numbers 
const Sum = nos => nos.reduce((a,b) => a + b, 0);
document.write(Sum([8, 34, 6, 29, 2, 1]));
15

Calculating the average of a range of numbers

To calculate the average of a range of numbers, we first sum them up and then divide them by the total count/length of the numbers. The reduce() method in JavaScript makes this process quite easier. 

//calculate average 
arr = [1,2,3,4,5,6,7,8,9,10,11,12]
let avg = (array) => array.reduce((a, b) => a + b) / array.length; 
document.write(avg(arr));
16

To get maximum value

Given a spread of numbers in an array, we are expected to return the number with the highest value. To do this, we use the max() function and the spread operator (...). The spread operator allows an expression to expand in places where multiple elements/arguments are expected.

//max number 
const maxnum = nos => Math.max(...nos); 
document.write(maxnum([5, 10, 15, 20, 25, 30, 35]));
17

To get the minimum value

This function is just the opposite of getting the maximum value: we want the minimum value.

//min number 
const minnum = nos => Math.min(...nos); 
document.write(minnum([5, 10, 15, 20, 25, 30, 35]));
18

Reversing a string

JavaScript has a method for reversing arrays. It is called reverse(). Unfortunately, it does not work on strings. To reverse a string, we first have to convert it into an array using split(), perform the reverse operation, then convert it back to a string using join().

//reversing a string 
let strreverse = str => str.split('').reverse().join(''); 
document.write(strreverse('This is a reversed string'));
19

Calculating a random number from a range of numbers

Using Math() function, here we get a random number from a range of numbers

//calculating a random number from a range of numbers
let a = Math.floor(Math.random() * (45 - 35 + 1)) + 35 
document.write(a);
20

Converting a string to an array

To convert a string to an array, we use the split() method. split() divides a string into an array of substrings. split() accepts a separator as one of its parameters to determine where each split should occur.
If the separator is missing, the split returns the entire string.

//converting a string to an array 
let str = 'This is a string'.split(' '); 
document.write(str);
21

Executing a function on every element of an array

To perform a function on every element of an array, we will use the forEach() method.

let letters = ['X', 'Y', 'Z']; 
letters.forEach(function (e) { 
  document.write(e); 
});
22

Multiple Variable Assignment

JavaScript is flexible enough to allow us to reassign variables – on a single line:

//multiple assignment 
let [w,x,y,z] = [30,84,28,"BABY"] 
document.write(w, x, y, z);
23

The odd integer

In this program, an array comprises of integers, either odd or even numbers, except for a single integer. This integer is an outlier. The program identifies this outlier and returns its value.

//program to identify an outlier 
const Outlier = n => { 
  let odd = n.filter(x => x % 2 != 0), even = n.filter(x => x % 2 == 0); 
  return odd.length == 1 ? odd.pop() : even.pop(); 
}
document.write(Outlier(([2,6,8,10,3])));
24

Sort an array by string length

Given an array with words of varying length, we will sort out the words by arranging them from shortest to longest.

//sort words from shortest to longest 
let sortByLength = arr => arr.sort((a,b) => a.length - b.length); 
document.write(sortByLength(['Attempt', 'Life', 'Not', 'Me', 'Again']));
25

Categorizing new members

A new club has two categories of membership, Senior and Open. We need to place new members into any of the categories. To be a senior, a member must be at least 55 years old and have a handicap greater than seven. In this club, handicaps range from -2 to +26, the better the player, the lower the handicap.
Each input for a single member consists of age and handicap.

//open or senior 
const openOrSenior = 
    (members) => members.map(([age, handicap]) => (age >= 55) && (handicap > 7) ? 'Senior' : 'Open') 
document.write(openOrSenior([[45, 12],[55,21],[19, -2],[104, 20]]));
26

Checking for Xs and Os

This program checks to see if a string contains the same number of Xs and Os. The return value is a boolean and is case insensitive.

//checking to see if a string has the same number of Xs and Os 
let XO = str => str.toLowerCase().split('x').length === str.toLowerCase().split('o').length; 
document.write(XO("xxxtooo"));
27

Checking for odd and even numbers

This checks if a number is even or odd. The return value is a boolean. It returns either true or false.

//program to check for a if a number is even or odd 
const isEvenOdd = num => num % 2 === 0; 
document.write(isEvenOdd(3));
28

Scroll to the top of a page

To write a program that allows us to scroll to the top of a page, we need the window.scrollTo() method. This method takes the x and y coordinates of the screen. When we set these coordinates to 0 and 0, they take us straight to the top of the page.
Note: It does not work with Internet Explorer

//scroll to the top of the page 
const toppage = () => window.scrollTo(0, 0); 
toppage();
29

Check if a particular day is a weekday

JavaScript has inbuilt date functions. These make it easy for us to manipulate dates and calendar functions. One such is the getDay() function. We can use it to get a particular date, and with a little calculation, we can ascertain if that date falls on a weekday.
The result of this is a boolean.

//to check if a particular day is a weekday 
const wkday = (date) => date.getDay() % 6 !==0 
document.write(wkday(new Date (2021, 2, 22)));
30

To check for palindrome

Palindromes are words that are spelt the same when reversed. We can check for palindromes in a simple one line statement.
The output of this is a boolean.

//program to check for palindrome 
const isPalindrome = str => str === str.split('').reverse().join('');
document.write(isPalindrome('civic'));

Though one-liners are cool to use, and sometimes to show off, they have some restrictions.

  • They should not be complex, which makes them harder to debug and maintain.
  • They are ideal for simple and straightforward statements.

Conclusion

Understanding of inbuilt functions plays a prominent role in writing shorter and efficient JavaScript code. For example, one-liners paired up with clean UI elements is a recipe for an outstanding mobile app.
Arrow functions, introduced in ECMAScript 6 (ES6), are also fun writing shorter functions. They take only one statement that returns a value. We also need brackets, the function, and the return keyword, which turns them into the perfect syntax for one-liners.
Ternary operators also cut down the overuse of ‘if’ in conditional statements, allowing simple logical statements to fit in just a single line.

On the path to pro-level JavaScript one-liners are a proof that even the basic syntax of JavaScript is packed with huge potential. We hope we just helped a creative programmer get closer to reaching great heights.

For more hands-on experience with developer thoughts or programming tips, please tune in to our blog page.

Author

Ivaylo Ivanov

Ivaylo loves Frontend implementations. He is eager to construct interfaces that users love; pixel-perfect. In his day-to-day job, he caters to anything HTML, CSS, SCSS, or JavaScript-based on the frontend side. Complexity is not a problem, he masters VueStorefront implementations equally well to simple web apps or PWAs.
Experimentation with CSS and its' capabilities is Ivo's passion. Be it animated elements, or SVG animations - he loves it!