Syndicate

Feed

Truthy and falsy in JavaScript

The purpose of this article is to help me and perhaps yourself differentiate between true, truthy, false and falsy in JavaScript. If you read through the article, in the end you will face two fun challenges. Good luck ;-)

The values true and false are booleans. The simple (often called primitive) data types in JavaScript are: numbers, strings, booleans (true or false), null and undefined. Remember to always write these two keywords — true and false — in lowercase. JavaScript is case sensitive.

With the use of certain operators, true is treated like 1 and false like 0. In your Firebug console, you can verify this.

console.log(true + 1); // outputs 2
console.log(true == 1); // outputs true
console.log(true === 1); // outputs false. true is not the number 1. 
console.log(false + 1); // outputs 1
console.log(false == 0); // outputs true
console.log(false === 0); // outputs false. false is not the number 0.

Hence, (false == 0) is true, but (false === 0) is false.

Type coercion is used in JavaScript with the == and != operators. From Wikipedia: “There are two types of type conversion: implicit and explicit. The term for implicit type conversion is coercion. The most common form of explicit type conversion is known as casting.” What this means is that true and false are converted to numbers before they are compared to a number. When comparing to any of these values: 0, null, undefined, '', true and false, Douglas Crockford, in JavaScript: The Good Parts, recommends the use of the === or !== operators. In JSLint, there is a “Disallow == and !=” option, which requires the use of === and !== in all cases.

Truthy and falsy are what we use to determine the result of a conditional expression. They are what we use to determine its result, they are not the result.

Here is what is falsy in JavaScript:

  • false
  • null
  • undefined
  • The empty string ''
  • The number 0
  • The number NaN (yep, 'Not a Number' is a number, it is a special number)

Everything else is truthy, and that includes Infinity (which is another special number, like NaN), and all Object objects and Array objects, empty or not.

In a conditional statement, conditions are evaluated from left to right. In the case where we have if(condition1 && condition2 && condition3...), if the first condition is falsy, the second condition is not evaluated. For this reason, it is wise to order the conditions so that the condition most likely falsy, or strict, is put first, and the most processing-intensive condition is put last.

In a conditional statement of the form condition1 || condition2 || condition3... , if the first condition is truthy, then the second condition is not evaluated.

That behaviour has been coined short-circuit evaluation. JavaScript, like any other programming language, is efficient, hence stops evaluating a logical expression as soon as the result is determined.

The Boolean operators || and && behave differently in JavaScript than they do in PHP. In PHP, the result of a conditional is either TRUE or FALSE. In JavaScript, the conditional will return the actual value of the expression that stops the evaluation. In an if statement of the form if (condition1 || condition2), if condition1 is truthy, then the result of the condition is true. But, when we use the conditional in a statement, that is, when we assign the conditional to a variable, then condition1 is the result. It is assigned to the variable.

Boolean operators in PHP and JavaScript languages
Language Short-circuit operators Value
JavaScript && , || Last value *
PHP && , and , || , or Boolean

* : Last means 'the expression that stops the evaluation'.

Here is an example:

var myCar = car || {};

If car is defined, and not an empty string, nor the number 0, it is truthy, hence it stops the evaluation, and its value is assigned to myCar. If car was falsy, then myCar would be initialized to an empty object.

Here is another example:

var myValue = 0 ;
var yourValue = 5 ;
var herValue = 8;
if (myValue || yourValue || herValue) {
  /* This code here will be executed. */
}

Since the result is the expression that stops the evaluation, then the result of myValue || yourValue || herValue is yourValue. Hence, the following code is perfectly equivalent:

if (5) {
  /* This code here will be executed. */
}

The number 5 is truthy, so the code between the curly braces is executed.

First question

Take a look at this code:

var myName = 'Caroline';
var yourName = ''; // an empty string, hence it is falsy
if (yourName && myName) {
  /* Code placed here will never be executed because yourName is falsy. */
}
if (yourName || myName) {
  /* Code placed here will be executed because myName is truthy. */
}
newName = myName || yourName;
console.log(newName); // outputs 'Caroline'
newName = yourName || 'John';
console.log(newName); // outputs 'John'

What happens now when we assign something like this to newName...?

var myName = 'Caroline';
var yourName = ''; 
var newName = myName && yourName;
console.log('newname is %o', newName);
alert(typeof newName);

The result is an empty string. Why is this so, you think?

Firebug console log and alert box
Hint: Nothing mysterious going on here. The explanation is in the article. Explicitly so.

Click here to reveal the answer.

Bonus challenge

How about this code...

var myValue= 6;
var yourValue = 5;
var hisValue = 0;
var herValue = 'the best';
var newValue = myValue && yourValue && hisValue && herValue;
console.log('newValue is %o', newValue);

newValue will be equal to what, and why?

Click here to reveal the answer.

[]

This tutorial was helpful to you? Post a comment and/or donate. Thank you.

Last edited by Caroline Schnapp about 13 years ago.

Comments

Perl and default values

Perl treats boolean assignment the same way. I really like this, as it conveys more meaning, but I understand why PHP didn't do it that way (much simpler to grok).

One place where you might use this behavior is to assign default values.

In Perl, you would use something like "anArgument ||= 5;" to assign the value 5 if an argument was falsy, whereas in javascript you have to use the longer "anArgument = anArgument || 5;" to get the same result. Don't you love Perl? :)

You explanation was great, I had no trouble completing your assignment.

P.S.: I read you more often now that you're on http://informatiquelibre.info/

I have seen that assignment operator before

Bonjour Robin,

I never touched Perl. Don't know where I was when it was popular. Maybe in a hybernating capsule. It took me a while to become interested in the Web — and in web design. I was a programmer but not for the web. I think that C++ might use this operator but to do something altogether different and very binary. Like applying an OR with oneself bit par bit.

P.S.: I read you more often now that you're on http://informatiquelibre.info/

I wander who added me there. I think that was done after my visit to Koumbit headquarters for a Drupal 5@7. One that I remember very fondly.

The values true and false

The values true and false are booleans. The simple http://e-papierossy.com.pl/en/e-papierosy/76-e-papierosy-gombit-423456.html (often called primitive) data types in JavaScript are: numbers, strings, booleans http://e-papierossy.com.pl/en/e-papierosy/99-e-papierosy-gambit-1221.html (true or false), null and undefined. Remember to always http://e-papierossy.com.pl/en/e-papierosy/80-e-papierosy-gambit-123445.html write these two keywords — true and false — in lowercase. JavaScript is case sensitive.

boolean

I see one problem with the code in your examples. It is not readable, at least it is not readable for me. If you really care about that people should easily understand the code you write, you should not write the code like this.

for example, what would this code snippet mean?

if (yourName && myName) {
  // some code here 
}

You would assume that if we both tell our names then the code will be executed.. but that's not true, because my name can be "0" and you are screwed.

so, the easiest way to make the code more readable to use boolean (or integer) values inside if statements.

if (yourName.length && myName.length) {
  // some code here 
}

this way you do not need to know the truethy and falsy thing about strings.

Numbers works nicely as boolean values, but always treat (myValue && yourValue) as boolean, do not use it as an integer. You should not care about what is the exact value..

But thanks for the nice tutorial, it is really good, I learned a lot from it. And now I will be more careful with boolean values in javascript..

The aim of this tutorial

this way you do not need to know the truethy and falsy thing about strings.

The aim of this tutorial is to be able to determine the truthiness of primitive data types and any JavaScript object.

PS: Someone who is not logged in will not be able to type in a name already used by a registered member. You're having trouble logging in?

Is Number 0 falsy???

I am running the test before and I doesn't seem that my browser is taking 0 as false!

function testMe() {
var myValue = 5-5;
var zValue = 0;

if (myValue) {
console.log("0 Is falsy")
}else {
console.log("0 Is NOT falsy")
}

if (zValue) {
console.log("0 Is falsy")
}else {
console.log("0 Is NOT falsy")
}

if (0) {
console.log("0 Is falsy")
}else {
console.log("0 Is NOT falsy")
}
}
0 Is NOT falsy
0 Is NOT falsy
0 Is NOT falsy

Re: Is Number 0 falsy???

@Fly by night, you've got it backwards. The "if" branch is executed if the condition is truthy, and the "else" if it's falsy. So you should have:

if (myValue)
    console.log("0 Is truthy (i.e., NOT falsy)");
else
    console.log("0 Is falsy");

It was wise to order the

It was wise to order the conditions so that the condition most likely falsy International Moving Company

Great site.How can possible

Great site.How can possible such this kind of nice post?I think he has vast knowledge and more experience in this field.Really nice post also thanks who published this.

I am also building new sites

I am also building new sites all of the time and getting good results by using natural methods. I look forward to future updates. Once again thanks. Keep smiling

Nice Blog

Wow! This blog looks just like my old one! It's on a totally different topic but it has pretty much the same page layout and design. Excellent choice of colors!

find out more abt Daisy Suites

Check out district 13 Daisy suites. Good buy!
Daisy suites

The blog is really

The blog is really appreciable and i like to keep on visiting this site once again that it would help me in further thanks for sharing the info.

This really is this kind of

This really is this kind of a awesome resource that you're offering and you give it away for totally free. I take pleasure in seeing sites that realize the value of supplying a prime resource for absolutely free. I truly loved reading your post.

blog

Un tel message extraordinaire, que je viens d'obtenir la plupart de vos articles. Mais j'ai trouvé ce post est presque certain que mes recherches, j'ai eu l'information la plus utile. Il est vraiment intéressant de lire ce post en particulier. Je veux juste que vous avez apprécié les efforts de la grande.

Nice tips

Advantageously, the article is really the best on this notable topic. I harmonize with your conclusions and will thirstily look forward to your approaching updates