6 One Liner Hacks In JavaScript

Introduction

Today I'll discuss the few one-liner codes used in JavaScript that will definitely ease your work while writing JavaScript. These one-liners are,

  • Scroll to top
  • The number is even or not
  • Capitalize a string
  • Random string
  • Extract the Domain Name from an email
  • Operator type

So let's start discussing these one by one.

Scroll to the top

You can use the window.scroll() method to automatically scroll to the top. Provide parameters x and y as 0.

const goTop= () =>window.scrollTo(0,0)

Call this function on any button/icon click event.

The number is even or not

Check if a number is even or not.

const isEven = num => num%2===0

Even

Capitalize a string

Javascript doesn't have an inbuilt function for capitalizing the string. So for this purpose, we can use the below one-liner code.

var st="capitalise me"
st.charAt(0).toUpperCase()+st.slice(1)

Capitalize a string

Random String

If you will ever need a temporary random unique string you can use this one-liner random string code

var randomstring= Math.random().toString(36).slice(2)

Random String

The best example is to generate an OTP

Extract the Domain Name from an email

simply use a substring method to extract the domain name from any email.

var email = "[email protected]"
var domain=email.substring(email.indexOf("@")+1)

Domain Name

Operator typeOf()

This simply shows you how you can check the type of data in Javascript.

console.log(typeof("Abhishek"))

Operator type

console.log(typeof(07))

Console

console.log(typeof(true))

Boolean

Conclusion

I hope you all understand these with the given examples better now and try to implement this in your projects and also will provide you with some more hacks of these types in the next article.

Till then, Happy Coding :)