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 5 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.

Truthy

Thanks very much for an excellent explanation.
Also I much prefer your confirmation sum to trying to sort out some of the weird characters that others pop up

well, i'm happy to find you

well, i'm happy to find you article. it really helps me. It's a excellent post. i will have a try according to what you said.Thanks for sharing such a wonderful piece of information.
The Simpsons Seasons 1-24 DVD Box Set |
true blood seasons 1-6 dvd box set |
doctor who seasons 1-7 dvd box set

It was wise to order the

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

Jual jaket online keren murah terbaik

It was wise to order the

It was wise to order the conditions so that the condition most likely falsy PaketLiburankeBali.org GigaJava.com

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");

Positive site, where did u

Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work.
2003 hayabusa frame

RE: good side

There are so many comments here that are really interesting and conducive to me thanks
for sharing a link especially for sharing this blog. online casino spielgeld||casino spiele onlie

good one

prestige casino || online spielothek
Please add good good information that would help others in such best way.This post is exactly what I am concerned.

Thanks for the marvelous

Thanks for the marvelous posting! I truly enjoyed reading it, you can be a great author.I will make sure to bookmark your blog and may come back someday Thanks for a great post and interesting comments. renovation cuisine

This article makes me so

This article makes me so hard

Worth Bookmarking

Great Post. I have not been visiting the site recently. Took a visit again and there were some great

comments on the site. Excellent post. Keep up the good work.

It was wise to order the

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

I am student of finance and

I am student of finance and like to learn more about finance but now a days I am interested to learn about java so can any one please refer me a book by that I can learn basic java or can get the proper path to learn.
UAE equity research

Try proof reading a couple

Try proof reading a couple of times before publishing. Keep writing though.This is like my third time visiting your Blog. You should write more please, this information will help me and others. IDI qualitative methods

Worth Bookmarking

Twin Fountains EC is a short drive away from Woodlands and Admiralty MRT Station. Future residents will be able to walk to the nearby Vista Point or a short drive to Causeway Point for some family fun and gatherings. A truly unique lifestyle awaits you.
Twin Fountains

This is the ideal post for

This is the ideal post for someone who desires to be familiar with this subject. You certainly place a new turn on a topic that’s been on paper about for years Belleville desert boots

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

Thanks a lot

It is nice to know about it this is useful information. And such blogs makes us familiar with the whole world. Thanks a lot for sharing your vast knowledge.. college paper writing service

I am impressed

Bartley Ridge has full and unique facilities, which includes a guard house, clubhouse, children’s playground, swimming pool, piano room, pool room, indoor gym, hydrotherapy beds, hydrotherapy baths, reading room, function room, onsen, jacuzzi.
Bartley Ridge

cheap essay writing services

Most university, college and high school students have cheap essay writing services benefited from having a coach at some point in their lives, either as a member of sports team, or as a participant in an individual sport.

Javascript

JavaScript is a very complicated thing. There are many different programming language, but the javascript is the worst. I do not like. In addition, a very resource consuming! Horrible ...

Good thoughts and well-written

Belgravia Villas has full and unique facilities, which includes a guard house, clubhouse, children's playground, swimming pool, Aerobic/Yoga room, piano room, pool room, indoor gym, hydrotherapy beds, hydrotherapy baths, reading room, function room, onsen, jacuzzi.
Belgravia Villas

Ecopolitan EC will be

Ecopolitan EC will be accessible with Punggol MRT Station as well as Punggol Bus Interchange. It is also right beside Tampines Expressway(TPE). Ecopolitan EC is also near to Marina Country Club, Sengkang Riverside Park and Sheng Siong hypermart in Punggol Central.
Ecopolitan EC

Great Post

Just want to say your article is as astounding. The clarity on your publish is just excellent and that i can think you are knowledgeable in this subject. Fine together with your permission allow me to take hold of your feed to stay up to date with approaching post. Thank you 1,000,000 and please carry on the gratifying work.
Corals At Keppel Bay

Jewel at Buangkok is a new

Jewel at Buangkok is a new and upcoming condo located in Buangkok Drive and Sengkang Central area, within a short walk to Hougang Green Shopping Mall and a short drive to Compass Point. With expected completion in mid 2016, it comprises of TBA towers with TBA units and stands TBA storeys tall.
Jewel at Buangkok

Future residents will be

Future residents will be able to walk to Jurong East MRT Station which is located right beside it. Also, nature awaits your family and friends at the Jurong Lake Park and the Jurong Country Park. Also, the ultimate nature awaits you the Japanese Garden.
J Gateway

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!

Authentic Jordan Sneakers

Online Sneaker Boutique, specializing in authentic Air Jordan Retro's and other rare Nike products. Pre-Orders accepted...123

Interesting article. Glad I

Interesting article. Glad I found it. Also check out Visit Corals at Keppel Bay

This is a great inspiring

This is a great inspiring article.I am pretty much pleased with your good work.You put really helpful information. Keep it up. thesis editing

find out more abt Daisy Suites

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

Future residents will be

Future residents will be able to walk to the existing Bugis MRT. With such a short drive to the city area as well as the orchard and bugis area, entertainment for your love ones and family will come at a stone’s throw away.
DUO Residences

Designed by renowned

Designed by renowned architect Ole Scheeren, the project is connected to Bugis MRT Interchange that will link the East-West Line and the upcoming Downtown Line. Duo
Residences has full and unique facilities, which includes a guard house, clubhouse, children's playground, swimming pool, piano room, pool room, indoor gym,
hydrotherapy beds, hydrotherapy baths, reading room, function room, onsen, jacuzzi.
DUO Residences

Thanks you, this is one of

Thanks you, this is one of the most interesting blogs that I have ever seen. Interesting article, Funny comment. Keep it up!
Jewel at Buangkok

http://www.dissertations-help.org

Oh! Amazing and really rich content and very useful information. I got it my solution from over here. I highly recommend his/her workings with the useful informative information. Thanks a lot………..

Thanks for sharing some

Thanks for sharing some ideas in your post entitled "Truthy and falsy in JavaScript" I will visit your site again.
Corals At Keppel Bay
D'pristine

In almost variety of

In almost variety of crafting as well as business presentation you wish to believe penning dissertation regarding the institutional framework (the university or), with your target market (that are checking out your personal composition). popular karen millen dresses outlet

my thoughts

As our JavaScript takes on more and more responsibilities, we need a reliable codebase—one that is thoroughly tested. Integration tests focus on how the pieces of an application work together. Jurong Gateway

hank you for your wonderful

hank you for your wonderful sharing advice and tips on how to use Ajax Drupal 6 . much appreciated

In almost variety of

In almost variety of crafting as well as business presentation you wish to believe penning dissertation regarding the institutional framework (the university or), with your target market (that are checking out your personal composition).

I think the whole cloud

I think the whole cloud service is wonderful. Its a great way to get more information and files from different computers without downloading the files. You can also back up your files with out the worry of losing anything. proofreading for writers .

I am often to blogging and i

I am often to blogging and i really respect your content. The article has really peaks my interest. I am going to bookmark your site and preserve checking for new information. www.welivebetter.com.

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.

Future residents will be

Future residents will be able to walk to the existing Bartley MRT in the Circle Line. With such a short drive to the city area as well as the orchard and bugis area, entertainment for your love ones and family will come at a stone’s throw away.
Kensington Square

future

java scripts we must learn how to use it property. sengkang new ec launch ecopolitan ec

Skypark Residences is a

Skypark Residences is a 99-years leasehold Sembawang EC development located at Sembawang Crescent / Sembawang Drive in District 26. With expected completion in mid 2016, it comprises of 9 towers with 502 units and stands 15 storeys tall. It is a short walk away from Sembawang MRT Station.
Skypark Residences

After reading your post, I

After reading your post, I have learned that type coercion is used in Javascript. Thanks a lot for sharing. I will share this site to my friends.
Guocoland Tp180
http://www.youtube.com/watch?v=Lu4IUfW2qK4

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.

wow, nice post about java.

wow, nice post about java. Im still learning java and this post helped me a lot.

Its very true post. Thanks

Its very true post. Thanks for sharing.

For vehicle owners, Yuan

For vehicle owners, Yuan Ching EC takes less than 30 minutes to drive to the business hub and vibrant Orchard Road shopping district, via Pan-Island Expressway (PIE) or Ayer Rajah Expressway(AYE). Jurong West EC

Very very nice! Thank!

Very very nice! Thank!

oh yeah! Thank!

oh yeah! Thank!

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <css> <html> <javascript> <mysql> <php> <span> <a> <b> <i> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <sup> <sub> <dd> <del> <blockquote> <img> <q> <p> <div>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <css>, <html>, <javascript>, <mysql>, <php>, <rails>, <ruby>.

More information about formatting options

CAPTCHA
I have to wonder if you're a human spammer or a machine, or less likely someone who cares to leave his or her thoughts behind.