JS Or statement question

Hello,

I’m hoping someone could clear something up for me.




    var book = {
        "title" : "The Restaurant At The End Of The Universe"
    };



    var returnVal = book.title || book.hello;

    alert(returnVal);


My question is this, when the or statement is evaluated it then returns the value of book.title as a string.
I always thought asking a boolean question would result in a true or false, and not a string.
And is this something that pertains just to JS?

many thanks,

Stefan

A boolean question would be:


if(!book.title || !book.hello ) {
 // when false
} else {
 // when true
}

Some good tutorial around this boolean thing:
http://www.quirksmode.org/js/boolean.html

in this case you are checking for the existence of each property and returnVal will take the value of the first property that exists in the chain of "or"s.

what exactly are you aiming to do?

“The Restaurant At The End Of The Universe”

I assume, if you are very hungry, you don’t want to travel a lot of lighyears to get to this restaurant :wink:

@Kalon

Aha object detection, I’m still picking up the finer details of JavaScript, not building anything in particular at the moment just following books and trying out examples.

I’ve used Java in the past so this syntax is a bit alien to me, I always thought asking questions like this would return a boolean value, but JavaScript let you work more dynamically with datatypes.

@bulevardi
Way too lazy to travel that far for a bite to eat, I was going for the hitch hikers guide to the galaxy but plumped for a later book.

thanks for all the help guys :slight_smile:

you’re welcome :slight_smile: