Skip to main content

15 Helpful JavaScript One-Liners

 Whether you’re new to JavaScript or a more seasoned developer it’s always good to learn something new. In this article, we’ll be going over a collection of JavaScript one-liners that hopefully help you tackle some of the daily JavaScript problems that you’ll eventually run into.

Hopefully, you learn a thing or two!

1. Generating a random number within a range

Getting a random value in JavaScript can be easily done with the Math.random() function. But what about a random number in a certain range? There’s no standard JavaScript function for that. The following function can be used to solve this problem.

Note that the max value is included in the range. If you want to exclude the max from the range you can remove the + 1 from the function.

2. Toggling a boolean

Toggling a boolean value is one of the oldest tricks in all of the programming books. A very basic programming problem, that can be solved in a lot of different ways. Instead of using if-statements to determine what value to set the boolean to, you could instead use the function below — which is the cleanest way in my opinion.

3. Sort the elements of an array in random order

Sorting the elements of an array in random order is can be done by using the Math.random() function. This is a very clean solution to a common problem. However, this way of sorting should not be used to achieve complete randomness. The sort() function should not be used for this. You can find more info about this topic here.

4. Capitalizing a string

Unlike other popular programming languages like Python, C#, and PHP JavaScript doesn’t have a function that allows you to capitalize a string. However, it’s quite a basic function that gets used a lot. You can put in a word or a complete sentence to this function, as long as it’s a string.

5. Check if a variable is an array

There are several ways to check if a variable is an array, but this is my preferred way to do it — clean and easy to understand.

6. Extract hostname from URL

Although this one is technically not a one-liner, it’s still a very helpful function. This can be useful for checking if a link is external or internal. Based on that you could add different behavior or styling to certain links.

This function also works with URLs that contain a port number or query string.

7. Get the unique values in an array

A very simple, yet super neat trick to remove all duplicate values from an array. This trick converts the array that we use as the first parameter to a Set and then back to an array.

8. Checking whether all items in an array meet a certain condition

The every method checks whether all the items in an array meet a certain condition. This method takes a callback as its only parameter and returns a boolean.

Tip: if you only need one element in an array to meet a certain condition, you can use the some() method.

9. Formatting floats based on locale

Formatting floats can be done in several ways. However, if you’re working on an application that supports multiple locales the format might differ. The following one-liner supports formatting float for different locales.

Tip: if you need to support multiple locales you can add a third parameter to this function for the locale.

10. Updating the query string

Updating the query string can be extremely helpful when working with filters, for example. Here’s an example of how you can update the query string with JavaScript’s URLSearchParams interface.

Note that the window.location.search that’s passed to the URLSearchParams will keep the current query string intact. This means that, in this example, the key=value will be added to the current query string. If you want to build a query string from scratch, leave out the window.location.search parameter.

11. Only positive numbers allowed

There will be times where you want a variable to only contain positive numbers. Instead of having to use if-statements to check whether the number is negative, you can use the following one-liner:

This one-liner can be used instead of a code snippet that looks like this:

The Math.max() solution is much cleaner, right?

12. Show the print dialog

The following line of code will show the print dialog which can be helpful if you want to provide a user-friendly way for the user to print a certain page on your website.

13. Copy text to clipboard

Copying text to the clipboard is a problem that can be solved in various ways.

If you only care about supporting modern browsers, the following example would be sufficient:

This is a pretty clean solution that doesn’t rely on any DOM elements.

Note that this function is asynchronous since the writeText function returns a Promise.

However, if you want to support older browsers like Internet Explorer you’ll have to take this approach:

This solution relies on an input field as opposed to the previous, Promise based, solution.

14. Casting all values in an array

We can use the map function on an array to cast all of its items to a certain type. In the example, you’ll see that we first cast an array of string to an array of numbers. After that, we convert the number array to booleans.

15. Calculate the number of days between two dates

Calculating the number of days between two dates is one of these things that you’ll probably do more than once if you’re programming in JavaScript a lot. To save you the hassle of figuring out how this problem can be solved every single time you can use this function that does the hard work for you.

Due to the use of Math.abs() the order of the date arguments is irrelevant.

That’s it!

Now that you’ve reached the end of this list I hope that you learned a couple of new things. Hopefully, you can put a few of these tricks into practice. If you know a great JavaScript one-liner that’s not on this list, please let me know. I’d love to see some more great one-liners.

Thanks for reading!

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...