JAVASCRIPT

Javascript shortcuts for loops, conditions and return functions

Powerful JavaScript Shortcuts and Idiomatic Expressions With && and ||

javascript shortcuts

You see these idiomatic expressions in JavaScript frameworks and libraries. Let’s start off with a couple of basic examples:

Example 1: Basic javascript shortcuts with || (Logical OR)
To set default values, instead of this:

Use this:

Explanation:

  1. First, read the “Important Note” box below for a refresher on JavaScript’s False and True values
  2. The || operator first evaluates the expression on the left, if it is true, it returns that value. If it is false, it evaluates and returns the value of the right operand (the expression on the right).
  3. If theTitle variable is false, the expression on the right will be returned and assigned to the variable. On the other hand, if theTitle is true, its value will be returned and assigned to the variable.
  4. If theTitle variable is false, the expression on the right will be returned and assigned to the variable. On the other hand, if theTitle is true, its value will be returned and assigned to the variable.
  5. JavaScript False Values: null, false, 0 undefined, NaN, and “” (this last item is an empty string). Note that Infinity, which is a special number like NaN, is true; it is not false, while NaN is false.

JavaScript True Values: Anything other than the false values.
Example 2: Basic shortcut with && (Logical AND)
Instead of this:

Use this:

Explanation:

  1. The && operator first evaluates the expression on the left. If it is falsy, false is returned; it does not bother to evaluate the right operand.
  2.  If the the first expression is true, also evaluate the right operand (the expression on the right) and return the result.

It Gets More Exciting!
Example 3:
Instead of this:

Use this:

Explanation:

  1. If userName is true, then call the logIn function with userName as the parameter.
  2. If userName is falsy, call the signUp function

Example 4:
Instead of this:

Use this:

Explanation:

  1.  If userName is true, call userName.loggedIn and check if it is true; if it is true, then get the id from userName.
  2. If userName is false, return null.

Powerful Uses of Immediately Invoked Function Expressions (How Immediately Invoked Function Expressions Work and When to Use Them) IFE (pronounced “Iffy”) is an abbreviation for Immediately Invoked Function Expression, and the syntax looks like this:

It is an anonymous function expression that is immediately invoked, and it has some particularly important uses in JavaScript. How Immediately Invoked Function Expressions Work? The pair of parenthesis surrounding the anonymous function turns the anonymous function into a function expression or variable expression. So instead of a simple anonymous function in the global scope, or wherever it was defined, we now have an unnamed function expression.

It is as if we have this:
// Shown without the parentheses here:

// And with the parentheses here:

// An unknown variable assigned the value of a function, wrapped in a parentheses, which turns it into an unnamed function expression. Similarly, we can even create a named, immediately invoked function expression:

  1. Note that you cannot use the var keyword inside the opening pair of parentheses (you will get a syntax error), but it is not necessary in this context to use var since any variable declared without the var keyword will be a global variable anyway.
  2. We were able to call this named function expression both immediately and later because it has a name.
  3.  But we can’t call the anonymous function expression later, since there is no way to refer to it. This is the reason it is only useful when it is immediately invoked.

By placing the anonymous function in parentheses (a group context), the entire group is evaluated and the value returned. The returned value is actually the entire anonymous function itself, so all we have to do is add two parentheses after it to invoke it. Therefore, the last two parentheses tell the JS compiler to invoke (call) this anonymous function immediately, hence the name “Immediately Invoked Function Expression.”
Because JavaScript has function-level scope, all the variables declared in this anonymous function are local variables and therefore cannot be accessed outside the anonymous function. So we now have a powerful piece of anonymous code inside an unnamed function expression, and the code is meaningless unless we invoke the anonymous function, because nothing can access the code. It is the immediate invocation of the anonymous function that makes it powerful and useful.
You can pass parameters to the anonymous function, just like you would any function, including variables. The anonymous function’s scope extend into any outer function that contains it and to the global scope. Read my article, JavaScript Variable Scope and Hoisting Explained, for more.
When To Use Immediately Invoked Function Expressions?
To Avoid Polluting the Global Scope.
The most popular use of the IIFE is to avoid declaring variables in the global scope. Many JavaScript libraries use this technique, and of course many JS pros, too. It is especially popular amongst jQuery plugin developers. And you should use an IIFE in the top-level (main.js) of your applications.

In this first example, I am using it in the global scope to keep all my variables local to the anonymous function, and thus outside the global scope where variables can shadow (block) other already-defined variables with the same name (probably from an included library or framework). All of my code for the application will start in the IIFE:
// All the code is wrapped in the IIFE

— Note that you can also pass jQuery or any other object or variable via the parameter (the last 2 parentheses).
Use With the Conditional Operator
The use of the IIFE in this manner is not as well known, but it quite powerful since you can execute complex logic without having to setup and call a named function:

— Note the two anonymous functions in the conditional statement
— Why would you do this? Because it is powerful and badass.
— I purposely added enough space between each section so the code can read better.

 

Use it in Closures to Prevent Fold Over
I discussed this particular use of the IIFE before in my post, Understand JavaScript Closures With Ease. So I will copy the section of that code and reuse it here.

To prevent close over in for loops, we can use an Immediately Invoked Function Expression to prevent a common bug when closures are used with for loops:

To fix side effects (bug) in closures, you can use an IIFE, such as if this example:

 

 

CoffeeScript

example if, switch and for expressions (which have no return value in JavaScript) return a value. As in Perl, these control statements also have postfix versions;

Be good. Sleep well. And enjoy coding.

Share

8 Comments

  1. Rob

    Good job. Be careful not to make single line statements that are hard to read. It is sometimes best to keep one logical action per line, simply for other developers to be able to go into your code and understand what is going on quickly. The annoying statement from some senior developers “If you need to explain your code, you’re doing it wrong.” Not always the case. Sometimes it’s complicated no matter how you lay it out so it might as well be efficient. Most of these read well, though.

    We can simplify:
    (showName = function (name) {console.log(name || “No Name”)}) ();

    even further using an arrow function:
    (showName = (name) => {console.log(name || “No Name”)}) ();

    Reply
  2. Darshana

    Good work Kishor.
    I am already using these tricks while coding. Did not release these are tricks.
    Keep posting looking for more.

    Reply

Leave a Comment

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