Home » JavaScript » 5 nifty JavaScript tricks that you may not know

About Veera Sundar

5 nifty JavaScript tricks that you may not know

Over the years, I have seen several JavaScript techniques that are particularly clever. Here’s a short list of 5 such techniques that I have been using again and again. I hope it inspires you too to rethink how you write certain piece of code.

And, please note that some people may think clever coding impacts readability and they might be right. So, grasp the concept and apply it in your code wherever you think it helps.

1. 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.

if(fruit === 'apple' || fruit === 'banana' || fruit === 'chikoo'){
    doMagic();
}

Here’s a compact version of above code:

if({apple:1,banana:1,chikoo:1}[fruit]){
    doMagic();
}

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

2. !!

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,

if(!!document.addEventListener){
    doMagic();
}

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

3. 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?

if(param){
    foo();
}else{
    bar();
}

Here’s an alternative, short approach:

param ? foo() : bar();

yay!

4. 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 function three() won’t be called.

So, you go for if, obviously.

if(one()){
    if(two()){
        three();
    }
}

But let’s rewrite with this one:

one() && two() && three();

5. 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:

function doMagic(){
    var foo = 1,
        bar = 2,
        zoo = (function(){
            // some complex stuff
            // some more complex stuff
            return stuff;
        }()),
        baz = 3;
}

So, what do you think about these tricks? Do you think these are usefull or affect the code readability? Feel free to comment your thoughts.

Reference: 5 nifty JavaScript tricks that you may not know from our WCG partner Veera Sundar at the Veera Sundar blog.

Do you want to know how to develop your skillset to become a Web Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Building web apps with Node.js

In this book, you will get introduced to Node.js. You will learn how to install, configure and run the server and how to load various modules. Additionally, you will build a sample application from scratch and also get your hands dirty with Node.js command line programming.

HTML5 Programming Cookbook

In this book, we provide a compilation of HTML5 based examples that will help you kick-start your own web projects. We cover a wide range of topics, from graphics and animation, to geolocation and offline storage. With our straightforward tutorials, you will be able to get your own projects up and running in minimum time.

 

4 comments

  1. The example for !!

    if(!!document.addEventListener){
    doMagic();
    }

    isn’t very good. It does the same thing as

    if(document.addEventListener){
    doMagic();
    }

    !! is for type casting to a boolean, which matters if you’re trying to assign the reulting cast value to a variable.

  2. Although the tips are all quite clever, I would be careful with #3 and #4. Especially #4 and similar tricks to it, such as conditional function calls using the or operator ||, can lead to code that’s hard to follow.

    It would be better formatted as if(one() && two()) { three(); } which achieves the same result without looking so out of place.

  3. #4 relies on a side-effect, which is never a good idea. Compiler optimization may cause code to be executed in an order not intended.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


4 − = one

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Do you want to know how to develop your skillset and become a ...

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!
Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close