Picture of Paul

The first programming language I learnt many years ago was JavaScript; not long after I got the internet at home I stumbled across a site called bodytag and as soon as I saw what you could do with Web pages I wanted to know how I could make my own. I followed through a JavaScript tutorial and, equipped with my new knowledge of if statements and for loops, my love for JavaScript began.

It’s taken me many years to learn and discover many of the intricacies of the language and I’m still thrilled to stumble across clever programming tricks or find something new. A while ago I found a fun little JavaScript riddle involving JavaScript’s booleans.

I have a variable called myVar, and the puzzle is to work out what the variable is based on a couple of expressions:

>>> myVar
false

>>> myVar == false
true

>>> !myVar
false

>>> Boolean(myVar)
true

If you want to work out the puzzle for yourself then stop reading now!

At first glance it looks like myVar is the boolean false, when we print it out we get ‘false’ and when we compare it to false it evaluates to true. The tricky bit is when we get onto the third and fourth lines, when !myVar suddenly returns false. myVar can’t be false, otherwise not-ing it would turn it to true! Finally, passing it into the Boolean function also returns true!

So we know it can’t be false, because not-ing it returns true, and we know it can’t be true because equating it to false returns true!

The answer lies with the difference between JavaScript’s objects and primitives. JavaScript has a small collection of “primitives” which are the basic building blocks, they include number for numbers and string for a “string” of characters. boolean is one of JavaScript’s primitives. But JavaScript is an object orientated programming language, and provides us with functions for its built in primitives. Because a primitive is the basic building block the functions can’t be associated directly with them, so most of the primitives have Object “wrappers” which provide these extra functions.

The final piece of the puzzle is JavaScript’s coercion rules, where objects can be “coerced” into primitive values. Each of the Object wrappers can be used as functions to coerce the first argument into that primitive. This is what we did on the fourth line above; “Boolean(myVar)” coerces myVar into a primitive boolean value. There are only a very small group of things that will evaluate to false when passed to the Boolean function, among them 0, null and (obviously) false. One thing that is not in the list are objects, when the Boolean function is passed an object it always returns true.

Now we have all the pieces in place to work out what myVar is! The first line will look like this:

var myVar = new Boolean(false);

We use the new operator to create a new object. The unexpected results then come about because myVar is a Boolean false object rather than a boolean primitive, so that when we not or pass it to the Boolean function it is first turned into a boolean true primitive. Fun!

Paul.

[ comments ] [ past blogs ]

74 Responses to “javascript riddle”

  1. Rebecca Says:

    hey try http://www.blogmusik.net it’s free music… it is really cool and it works at school too.

  2. randy Says:

    this is really interesting – i haven’t seen a good explanation of Boolean objects and primitives in a long time. go javascript!

  3. mohammed dahya Says:

    hi every body were is the good one

  4. petrule Says:

    e super mssul acesta dar bagati camera foto,alte imagini decat capsoarele…si asa mai departe

  5. Jim Says:

    Nice riddle Paul and great explanation. I didn’t figure it out on my own. :(

    This and one of the questions on your jobs page (with the !!) are some neat tricks I have learned from you guys just by browsing the page. Thanks for keeping the geeky stuff coming!

    Jim A.

  6. Mike Says:

    I’m a developer, so I appreciate these blog posts, but not all of your users are. You guys continue to post technical blog posts, which appear when we log on. It doesn’t seem like good content to be throwing up to an ordinary user when they log in. Just my opinion.

  7. kaiser Says:

    tricky tricky. i was about to say “myVar could also be a string!” but i forgot about myVar == false.

    in the last year or two i’ve seen what js is capable of. it was also my first programming language as well, back in 99, but i never really knew or investigated its potential until all these nifty scripts starting popping up. i was living in the js stone age for a long, long time. now i gotta play catch-up.

  8. jaded Says:

    how do i turn off these annoying pop-ups from you guys? can you please post an article on that? i am tired of clicking that little X everytime i open meebo… can we see photos of sandy instead? she is cute

  9. Rj Says:

    hi all guys. I very enjoyed this blog. I’m the java developer, web programmist in Mongolia. i think java has very improved in Mongolia.
    do you know about Mongolia. Ex: Asia, GENGIS KHAAN,,, etc

  10. Sean O Says:

    See and I thought myVar was just returning a null value. Ya got me there!

  11. robotomus Says:

    this also works:

    myVar = new Object(false)

  12. ana Says:

    I am starting to study java and php, I was not able to understand everything, the website you recommended is really good, thanks a tot ;)

  13. Lee Helzer Says:

    I love the java script blog entries. They are always very informative. Keep up the great work!

    -Lee

  14. Richard Says:

    Yeah, I’d have to agree with a few people who have already posted so far. The meebo blog from time to time is intersting but mostly not something the normal user wants to read. Javascript, strings, booleans, and all that other junk isn’t what I want to read about first thing in the morning (or ever really). If it floats your boat that fantastic and more power to you, but for the rest of us, lets just town down the techno mumbo jumbo.

    Maybe an option to turn off the meebo blog would be something you folks should focus on instead of spending time posting up geek speak blogs.

  15. jeremy Says:

    i didnt read it but this chatting is really cool

  16. John Kiefer Says:

    Correction to Paul’s post:

    There is another value that Boolean() will convert to the value ‘false’ and that is undefined. Also, even though undefined evaluates to false as in

    var c; //c is now undefined;
    if (!c){ /* something happens */ }

    undefined will not registers as equal to false, i.e.

    if (c == false){ /* nothing will happen */ }

    var b = Boolean(c); //b is false and b == false will evaluate to true

    I love these Javascript tutorials.

  17. elaine Says:

    hey paul, congratulations on your first blog post! it’s great to have another name appear in the meebo blogs.

  18. bryan Says:

    Pretty fun.

    So… does this behavior add any power/convenience to the language besides the facilitation of JavaScript puzzles?

  19. sata Says:

    rubbish rubbish try agin this is so boring and that letter u wrote lol it bord me 2 sleep ha ha ha ha ha ha ha ha ha ha ha ha ha ha . rubbish boring bored me to sleep ha ha ha ha ha ha ha

  20. Damond Says:

    Just want to thank the entire meebo team for creating such a wonderful tool! Please keep it simple and small.

  21. Kevin Says:

    allways assum nothing.

  22. faithlessx Says:

    …and this is why I hate Javascript.

  23. Stacey Says:

    Is learnt a word?

  24. leto is cool Says:

    STOP POSTING THESE MESSAGES!!!!!!!THEY ARE SOOOOOOOO ANNOYING!!!!!!!!!

  25. Kaleb Says:

    haha, whoaaaaaa, nerd alert!! I didn’t get a single bit of that.

  26. ihatejavascript Says:

    these things are really REALLY annoying and seeing as how only about 1/3 of the people that actually use meebo get this or look this pointless stuff up and 2/3 really dont care and dislike having to X out of these comments seems really more of a problem to me than the riddles of javascript… maybe you guys should put more energy into figuring out how to fix that problem instead of posting geek speak about javascript. that sounds like a good idea now doesnt it? thanks

  27. Frank Says:

    ive been developing websites with Javascript for 5 years now, and i feel like a real idiot. i think i understand what your talking about, but im not quite sure.

  28. javastuff Says:

    see, i thought javascript is loosely typed and the “new Boolean(false)” isn’t really required. the whole time (even now) ii think myVar is just a string. i’m pretty new to javascript, therefore i’m probably just making a fool out of myself. =) cool riddle though, i find little nerdy surprises all over meebo.

  29. gray Says:

    i just attempted to log into AIM like 5 times with my user name and password through meebo. i did it careful and correct and couldn’t get through. i kept getting an error saying my password was incorrect

    but then i logged in with regular desktop-installed AIM on my dads computer and i got in fine.

    so i logged out of that, then came back to my computer, and then was able to log into meebo AIM just fine.

  30. sdfghrg Says:

    puta ka!

  31. Arun Says:

    lol i was thinking the second line checked if myVar is false or not (returning true) and ALSO set myVar to the answer of the check. sort of like:
    >>> myVar = (is myVar = false?) [>> myVar = true
    because the statement (is myVar = false?) returns true…

    hmm maybe i think too much, but i never learnt javascript as it is… i only learnt java and that’s not a strong point either. take care :)

  32. Feiteira Says:

    I am a computer programmer, I love programing and I like javascript.

    But I find these posts extremely annoying! When I’m using meebo I don’t want to be thinking about code. Simple as that.
    You guys, should reconsider, you’re about to loose big points in my book if you keep with these nerd-like posts. (And I doubt I’m alone)

  33. Satya Says:

    Awww.. you really done a great job.I hope i can develop some new in programming like u done ..

    With Best Regards
    Satya

  34. AlvinSongster Says:

    I can understand why some would not like the technological/programming blog entries, although I do. Maybe there could be a Profile option along the lines of, “Only show informational blog entries; block technical/programming blog entries”. Should be a piece of cake.

  35. Brian Says:

    Ever thought about getting a separate technical blog?

  36. Taylor Says:

    cool

  37. Taylor Says:

    So how did you come up with meebo anways?

  38. Amanda Says:

    hey…

  39. asia Says:

    hi

  40. asia Says:

    hi wats up

  41. Dan Says:

    Javascript is retarded.

  42. ljkljklh Says:

    hey yal

  43. usa! Says:

    wat up yal

  44. usa! Says:

    write back yal

  45. usa! Says:

    ok so lik one day, i saw this walrus. his name was wally the walrus. so he made a sound like arrff arr. u no? he wasnt very cute. you no who he was? my walrus! duh!

  46. princton Says:

    ….nerds are always around the corner. be watching out for them. im talking about how nerdy that paul guy is. dont ya think? im he didnt even spell learnd rite its not learnt! stay away from nerds cause u could become one too. i bet paul was born nerdy. Ha ha ha ha ha ha Ha ha ha ha ha ha Ha ha ha ha ha h Ha ha ha h Ha ha ha ha ha ha ha ha Ha ha ha ha ha ha Ha ha ha ha ha ha

  47. hey Says:

    hi

  48. hey Says:

    byich i cant spel the word rite but u no wat wrd im tryin to say. right?

  49. hi Says:

    thats not nice

  50. kat Says:

    ok i have got a problem…
    i can’t get onto my aim account!
    helpp meee pleasee!

  51. kat Says:

    also whenever i click on the “comment” icon at the end of your blog…it takes me away from the meebo screen instead of opening in a new window…idk just some issues i’m coming across. please help me if you can. thankss! :]

  52. Dilz Says:

    I don’t use Meebo that often, so I didn’t know what to make of the blog post at first…

    Anyway, I work in IT, but have always admired programmers and others who actually use a computer to make or do something. Yet, for some reason I’m still unable to throw my hat into the ring. My most memorable failed attempt to learn code ended when I couldn’t grasp the concept of C++ “classes” (6th Chapter!) from a “Sam’s 24h” book… I was just humming along until I hit that chapter. Up to that point, it was reasonably close to BASIC. C++ has remained just out of my grasp. It would seem that Java would be the language to try to learn now… yes? Ruby (inc. variants), perhaps?

  53. denise Says:

    i have no idea what that was.

  54. Martin M Says:

    this was a good read as far as i’m concerned.

  55. Ryan Says:

    Great post guys! Thanks! Great insights – keep them coming!

  56. Fanny Says:

    Paul really knows what he’s doing. Fun post!

  57. hi Says:

    hey write back

  58. Allie Says:

    I think if you don’t want to hear what the meebo staff have to say then don’t use their product. Simple as that. Keep up the good work guys!

  59. Tamlyn Rhodes Says:

    Yeah pretty cool demo. From reading some of the comments here I think what you guys need is a dev blog for posting gems like this and an announcements blog for posting service related news. Keeps everyone happy :)

  60. dare Says:

    Good job. Being able to access other networks from your end, is a welcome developement. Keep on with the good work.
    http://eaglesdigestmag.com

  61. 3zet blog Says:

    Great site guys, please let me know if you are interested in exchanging links with our sites. http://www.3zet.net/

  62. wizrd Says:

  63. wizrd Says:

    29,0″ width=”466″ height=”329″>

  64. PlusNet Web Portal Team - Blog Archive » Another JavaScript Riddle Says:

    [...] by meebo’s JavaScript Riddle blog post, here is another bit of weirdness I just came [...]

  65. masssage_videos Says:

    I don’t like javascript.I preffer nofollow

  66. masssage videos Says:

    javascript is very hard to do for me

  67. SEO Says:

    Sounds like fun :)
    Thanks for the tips.

  68. david Says:

    real nice

  69. Ellen Says:

    errr thanks…?

  70. meeblog » Blog Archive » metablog Says:

    [...] and I really like reading and writing technical blogs and our happy camper, popup predicament, javascript riddle, and ops tips are still among my [...]

  71. asian massage fan Says:

    yahoo started to use noffolow tag.I would say its definetelly beter than javascript tags.

  72. Home Terrorist Says:

    Good stuff, I my site has some stuff on JavaScript Injections

  73. Jacques Snyman | Website Design Says:

    Asian massage fan, I really dont get what you’re on about. The nofollow tag is to block search engine spiders from from following links (or transferring link-love for Pagerank in Google’s instance)

  74. Nizova Says:

    Nice post. As Jose Gonzalez sing “We’ll remain after everything’s been washed away by the rain”. :)