JavaScript Truthiness

JavaScript Terms – Part 2

JavaScript is different in many ways than other popular languages, for many reasons. It introduces many different terms as I mentioned in my previous post; Higher-Order Functions. That’s why in this post I am going to introduce two other common JavaScript terms; truthy and falsy.

But First… Introducing the Equality Operator

JavaScript has a boolean data type and the equality operator along with the greater than, less than, less than or equal, and greater than or equal to operators can produce a boolean type during assignment.

These conditions can be used inside the if, else if, for loop, while and do while loops to determine a condition. The condition can also be returned from a function in the form of a conditional boolean statement.

In languages like C#, you must use a boolean condition for those things mentioned above.

//C# and Java
if(a == b){
   //do something
}

In the code above Java and C# will compare a and b and if they are equal and execute the statements inside the body of the if statement. In those languages the condition must always be a boolean. This course is not about Java but it’s worth mentioning that, in Java, if a and b are of the type String then they must use the String.Equals method, nevertheless it is still a boolean condition.

In JavaScript, the condition is not required to be a boolean. The condition can, instead, contain any data type and any value.

When the condition is a boolean, things will behave as expected… sort of. I say sort of because JavaScript has two equality operators the abstract equality operator (‘==’) and the strict equality operator (‘===’).

The difference between the two operators can be seen in the example below.

let a = "5";
let b = 5;

console.log(a == b); //prints true to the console
console.log(a === b); //prints false to the console

As you can see above, one statement produces true and the other produces false.

This is an important distinction because it may not be what you intended. In order for both statements to evaluate to true both a and b must be of the same data type.

The abstract equality operator “==” does something called coercion to allow the evaluation to be true. It basically changes the right variable’s data type temporarily to the same type as the data type of the variable on the left side of the operator.

That may lead you to believe that you will know what to expect for any given mix of types but that is not quite so simple, as we can see in the example below.

var c = "true"
var d = true

console.log(d == c); //prints false to the console
console.log(c === d); //prints false to the console

You might have expected the first console.log statement to become a boolean type, but that is not the case at all.

Therefore, you should stick to using the strict equality operator most of the time.

Strict and abstract operators for greater than or equal to, less than or equal to, and not equal to (negation… !condition) are also available.

Truthy and Falsy

Like I said in the beginning of this post, JavaScript has different rules for the condition inside the if statement. The condition in the if statement can be any data type’s value. Some values evaluate to true and some evaluate to false. Because these values are not explicitly boolean, we say they are “truthy” or “falsey”.

That means they can be used as conditions inside of the if statement and we can expect certain behavior from them. In other words, we should know which values result in true and which values result in false.

Let’s take a look at a few.

function examineTruthyness(info, val){
  if(val){
    console.log(`${info} \'${val}\' evaluates to true`);
  }
  else
  {
    console.log(`${info} \'${val}\' evaluates to false`);
  }
}

let val;

examineTruthyness("EMPTYSTRING", "");      //false
examineTruthyness("SPACE", " ");           //true
examineTruthyness("EMPTYARRAY",[]);        //true
examineTruthyness("FULLARRAY",[1,2]);      //true
examineTruthyness("TRUESTRING","true");    //true
examineTruthyness("FALSESTRING","false");  //true
examineTruthyness("NULLVALUE",null);       //false
examineTruthyness("UNDEFINEDVALUE",val);   //false
examineTruthyness("ZEROVALUE",0);          //false
examineTruthyness("ZEROSTRING","0");       //true 
examineTruthyness("NONZEROVALUE",1);       //true
examineTruthyness("EMPTYOBJECT", {});      //true

You might have already guessed it but pretty much everything else not mentioned in the above falsy results will result in true.

So… you can use these values inside if statements to execute logic. However, just because they are truthy that does not mean they can be compared to the value true. That is a fact with either abstract equality operator or with the strict quality operator.

if([] == true) //will evaluate to false

As you can see truthy values are not the same as having the value true.

Summary

Beyond the explanations above there is not much to using booleans in JavaScript. They are just like the other languages.

If you find this post helpful please be sure to subscribe to my blog. You can also follow me on twitter @fernandozamoraj or linkedIn https://www.linkedin.com/in/fernandozamoraj/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: