Helpful Javascript Oneliners to Make Your Code Cleaner
Tags: javascript, programming, tutorial, code
Published: 2024-01-31 22:24:50

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 cool way to do more things with Javascript. In this article, we will be looking at over 12 Javascript one-liners that will make your code cleaner. They are simple, easy to remember, and show proficiency in using methods.


Lets go!

**Eligibility to vote**
This function checks if a citizen is eligible to vote. The minimum age of voting is set to 18. It uses a function 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);
```

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

```
let lastoccurance = 'Jerusalem'.lastIndexOf('e');

document.write(lastoccurance);
```

**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);
```

**No Fives**
This program aims to get the count of numbers within a certain 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))
```

**Find the length of the shortest word**
Given a string of text, this program 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"))
```

**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}.`);
```

**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);
```

**The sum of numbers**
To calculate the sum of numbers in a given array we use the reduce() function. The reduce() function like it's 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]))
```

**To get minimum value**
This is just the opposite of getting the maximum value. In this case, we want the minimum value.

```
//min number
const minnum = nos => Math.min(...nos);

document.write(minnum([5, 10, 15, 20, 25, 30, 35]))

```
**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)

```

**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 it's parameters to determine where each split should occur. 

If the separator is not given, the split returns the entire string.

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

document.write(str);
```

**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);
});
```


**Multiple Variable Assignment**
Javascript is flexible enough to allow us reassign variables and this can be done in a single line

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

## Conclusion
Understanding of inbuilt functions play a large role in writing shorter codes. 

Arrow functions, introduced in ES6, is also a fun way of writing shorter functions. They take only one statement that returns a value. Brackets, the function and return keyword are also not needed. This makes them the perfect syntax for one-liners. 

Ternary operators also cut down the overuse of 'if' in conditional statements, allowing simple logical statements to be written in just one line. 

To become a pro at writing one-liners, it is important to check these out and understand them.