12 Lines of JavaScript To Make You Look Like a Pro

Maxwell
Level Up Coding
Published in
2 min readOct 18, 2022

--

Javascript can do many amazing things, and there are many things to learn, today we introduce a few short and concise code snippets.

Determine if a number is odd or even

The modulo operator % does the job well.

Determine if a date is a working day

Check if a given date is a weekday.

Get Random boolean(True/False)

Using Math.random() will return a random number between 0 and 1, and then judging whether it is greater than 0.5 will get a value with a 50% probability of True or False.

Get Time From Date Object

Use the .toTimeString() method of the Date object to convert it to a time string, and then intercept the string.

Scroll to Top of Page

window.scrollTo() will scroll to the specified coordinates, if the coordinates are set to (0, 0), it will return to the top of the page.

Reverse the String

There are many ways to reverse a string, here is one of the simplest, using split(), reverse() and join()

Determine if the Current Tab Is Visible

The browser can open many tabs, the following code segment is to determine whether the current tab is an active tab.

Checks if the Specified Element Is Focused

You can use document.activeElement to determine whether an element is in focus.

Check if the Current User Supports Touch Events

Check if the Current User Is an Apple Device

You can use navigator.platform to determine whether the current user is an Apple device.

Get the Mean of All Parameters

The reduce() function can be used to calculate the average of all parameters.

Convert Fahrenheit/Celsius

Don’t be afraid to deal with temperature units anymore, the following two functions are the mutual conversion of two temperature units.

--

--

A front-end enthusiast, a development engineer willing to learn more about development techniques and collaborate to build better software.