6 One Liner Hacks In JavaScript

Introduction 

Today I'll discuss the few one-liners code 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 Domain Name from an email
  • Operator typeOf

So let's start discussing these one by one,

1) Scroll To Top - You can use the window.scroll() method to automatically scroll to the top. Provide parameter x and y as 0.

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

Call this function on any button/icon click event.

2) Number is even or not  - Check if a number is even or not 

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

6 One Liner Hacks In Javascript

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

6 One Liner Hacks In Javascript

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

6 One Liner Hacks In Javascript

The best example is to generate an OTP

5) Extract 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)

6 One Liner Hacks In Javascript

6) Operator typeOf() - This simply shows you how you can check the type of any data in Javascript 

console.log(typeof("Abhishek"))

6 One Liner Hacks In Javascript

console.log(typeof(07))

6 One Liner Hacks In Javascript

console.log(typeof(true))

6 One Liner Hacks In Javascript

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