Developer News, More

5 JavaScript Tricks You Need To Know

JavaScript

JavaScript  also known as ECMAScript, is a dynamic programming language. It is most commonly used as part of web browsers, whose implementations allow client-side scripts tointeract with the user, control the browser, communicate asynchronously, and alter the document content that is displayed.There are several JavaScript techniques that are particularly clever. Here’s a short list of 5 such techniques inspires you to rethink how you write certain piece of code.

Conditional function call

If a value is true, you want to call a function foo() otherwise you want to call bar(). You go for if, right?

Here’s an alternative, short approach:

yay!

 

IIFE

IIFE is short for Immediately Invoked Function Expression. It means, you define a function and then you call it immediately. IIFE helped me in some usecases where I don’t want to create a new function but I needed the logic to be inside a function block.

For example, lets say you are initializing variables and for one variable, the initial value needs to be calculated using some complex logic. If you don’t want to separate this calculation logic to a seperate function, but you still want to wrap it in it’s own block, you can IIFE. Like below:

A compact string comparision

Let’s say you want to check if a string value is present in a set of strings. You obviously go for a if statement as below.

Here’s a compact version of above code:

This trick works well only if you have a small set of strings to compare.

!!

Here’s a shortest way to convert any JavaScript value to its truthy / falsy representation – just use !!val. Very useful if you want to check if a value is a present or not.

For example,

But !! might confuse people with ! operator which has a different meaning. So make a good judgement before you use !! everywhere.

Chaining of function calls

You have three functions one(), two() and three(). You want to call these functions one after other, but only when a previous function returns a truthy value. For example, if all three functions returns a truthy value, then all will be called. But if the function two() returns false/null then functionthree() won’t be called.

So, you go for if, obviously.

But let’s rewrite with this one:

 

So this is our JavaScript tricks.Hope you like the post.

You Might Also Like