Few useful javascript tips, tricks and shorthands to make your code smaller

This article contains few handy tricks and shorthands for your everyday code in javascript. Using these shorthands you will be able to save few minutes for your girlfriend :P. Few of them also increases the readability of your code.

#Null check in objects

Instead of checking the properties and sub properties of an object one by one, you can use some shortcuts to get it done with minimum code and better readability.

#If else statement

Ternary operators are fast to write and also in executing. But long statements in it may hamper your readability.

#Conditional assertion

To insert value in a varible you may not have to check the existance of them; as there are shortcuts. Below is an example.

#Same variable multi condition

To check if a variable have few specific values or not, you dont have to write a long expression. Put the values in an array and check if the existing value of your variable is there in the array or not.
But over use of this will increase your garbage memory.

#Convert string to number

#Round a number

Without even using Math.ceil or Math.floor it’s possible to perform the same operations very easily and quickly.

1. Round a number upward to its nearest integer:

2. Round a number downward to its nearest integer:

#Shorthand with truthy and falsy

Know the falsy values in javascript.

#Array to CSV and vice versa

A shortcut to convert an array to a csv string and vice versa.

#Calling a function as a string

Executing a function and similar thing using strings and without using eval.

About This Author

Hello! I am Paul Shan, a JavaScript Expert, Full Stack and DevOps Engineer cum Consultant based out of Bengaluru, India.

  • Thanks for these!

    Correction to “Round a number upward to its nearest integer”

    ~2.8 // = -3
    -~2.8 // = 3

    • metalshan

      Thanks for notifying. Have corrected now 🙂

  • Travis Harris

    Math.ceil is not the same as -~ as -~ will increment an integer, while Math.ceil will leave it alone.

    Try it:

    • metalshan

      Thanks Travis. My bad. I’ve put the warning now!