Helpful Javascript Oneliners to Make Your Code Cleaner

barrisam

Barri

Posted on January 31, 2024

Helpful Javascript Oneliners to Make Your 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 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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

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"))
Enter fullscreen mode Exit fullscreen mode

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}.`);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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]))
Enter fullscreen mode Exit fullscreen mode

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]))

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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.

💖 💪 🙅 🚩
barrisam
Barri

Posted on January 31, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

JavaScript for of loop tutorial
javascript JavaScript for of loop tutorial

April 29, 2023

JavaScript for loop
javascript JavaScript for loop

April 10, 2023

JavaScript for in loop
javascript JavaScript for in loop

April 22, 2023