I enjoy perusing other people’s code to see how they approach whatever it is that they are trying to solve. The follow simplified function caught my eye:

function someFunc(a){
   void 0===a.prop&&(a.prop=20);

Looks like some esoteric stuff but makes a lot of sense when written like this:

function someFunc(a){
    a.prop = a.prop || 20;

Functionally these two expressions mean the same thing. The difference is that the author of the first line is being clever 😉

The two expressions listed above read as follows in plain english: if a.prop is equal to undefined then create the property if it doesn’t exist and set its value to 20, or just set its value to 20..

The second example is much easier to read but the first is what we’re interested in so lets dissect its meaning.

First, this part needs to be understood:

void 0

This represents the global primitive property undefined. Why write it like this? Well, it used to be that you could overwrite undefined by design or by mistake meaning that you could never rely on it being what it should be (though usually you could) – writing it like this guarantees that you would always be dealing with the true undefined primitive value. Modern browsers don’t allow you to do overwrite undefined anymore.

Next is:


Which of course is the strict equal operator which checks to ensure that the operands or not only equal but of the same type.



Of course this is a reference to the value held by the prop property of the a object.

So then, the author is comparing undefined to a.prop. This will return true or false. Ok, not so clever until we get to the next part:


This is where it all comes together – note the logical AND operator &&. As you would expect it evaluates the expression on the left first and this is the key to how this bit of code works. These are the two possible outcomes of evaluating the left expression:

  • For the expression void 0===a.prop&&(a.prop=20);

    1. if a.prop is undefined then we must evaluate the expression on the right! Since the right operand is grouped by parenthesis it must first be evaluated to determine its truthiness. By evaluating it we are setting a default value for a.prop.
    2. if a.prop is not undefined then the left operand is false and nothing happens! Consider that both operands of the logical AND operator are evaluated only if the left operand is true. If the left operand is false then the right operand is ignored.

Pretty cool way of making use of the && operator!

As a side note, if the property was missing from the object we would also get undefined so the code here would first create the property then set its default value.