Wednesday, August 14, 2013

Truthiness /falsiness and using them for default values

Javscript like any other language support boolean data type. But there is a concept of truthyness and falsyness which if used properly gives you tremendous power to write maintainable and expandable code easily.

Before we go ahead with using these concepts in our program, we will have a brief look at them.


Though Javascript supports boolean types, these are not the only values that you can use inside your decision control statements like if, for, while etc. Javascript also support using all your types (everything is an object, more on that later).  That means you can use absolutely any variable or literal in your decision making control structures for checking condition, it doesnt necessarily have to be of type boolean. 


An example of the same can be given as follows.

//Example 1 :
//Using strings in the decision control structure
var someString = ""              
if(someString ){                    //valid javascript
      alert('Inside string if')
}

//Example 2 :
//Using string variable which has a non blank string as value
var stringValue = "js-gotcha";//valid javascript
if(stringValue){
     alert('Inside stringValue ')
}

//Example 3 :
//Using object literal.
var obj= {};                           //valid javascript
if(obj){
     alert('Inside obj with value');
}

Well since you can use absolutely any variable type in decision control structure. Flow of execution is decided on the truthyness or falsyness of that variable.

So what is truthy or falsy.
Truthy: Something which evaluates to TRUE.
Falsey: Something which evaluates to FALSE.

Falsy Values
The following values are always falsy. 
1.     false
2.     0(zero)
3.     ""(empty string)
4.     null
5.     undefined
6.     NaN(a special Number value meaning Not-a-Number!)

Truthy values
All other values are truthy, including "0" (zero in quotes), "false" (false in quotes), empty functions, empty arrays, and empty objects. So easiest way to check if something is truthy is to check if it is not falsy in above list mentioned for its value.


Now that we have a brief understanding of what is truthy and falsy. Let's have a look at the examples that we saw earlier.

Example 1 uses string which has the value "" (blank string) which is falsy, hence you will not get the alert.

Example 2 uses a string which has a non blank string as its value. Hence you will see this alert.

Example 3 uses object initialized with object literal, which is truthy hence you will get this alert.

You can check the above examples here in action.

This covers first part of this article. Let us move to an interesting part where we can use this to our help.

As said earlier we can use absolutely any value in decision control structure, more interestingly we can use the concept of truthyness and falsyness inside your simple statements as well. 

An example of the same can be given as follows.

var size = options && options.size || 1; //valid javascript

Let's elaborate on what is happening here. If you use &&(AND) and || (OR) operators in your statements. Your statement are executed on the basis of truthyness and falsyness. 

This can be elaborated with different cases.
//Case 1 :
//Options is undefined
var options;
var size = options && options.size || 10;  //size gets value 10
alert(size);



//Case 2 :
//Options is object but doesnt have size as its property
var options = {};
var size = options && options.size || 10; //size gets value 10
alert(size);



//Case 3 :
//Options is object and have size as its property
var options = { size : 20};
var size = options && options.size || 10; //size gets value 20
alert(size);



This examples can be seen in action here.


In case 1, since options is not initialized to any value, it has a value of undefined which is falsy. Hence the statement execution of and stops at options and continue with the ||(OR) provided. Hence size has value of 10.

In case 2, options has a truthy value but since options.size is undefined. Execution continues to OR and size again has value of 10.

But in case 3, we have options object with a property named size. So executions stops at options.size and doesnt continue till OR. So size has value of 20.

Apart from assigning default values like this, this pattern of using truthyness/falsyness is useful in writing clean code(without any if) where you want execution of your flow to be proceeded depending on availability of value in some object. 

Thanks for reading. Any questions are welcome.