Nick Short
Nick Short

Reputation: 13

JavaScript assignment and conditional on one line

I'm following some code in a HTML5 games book and can't understand how this line of code manages to work -

mp3Support = "" != audio.canPlayType('audio/mpeg');

I've worked out it means the same as -

if(audio.canPlayType('audio/mpeg') !=  "") {
    mp3Support = audio.canPlayType('audio/mpeg');
}

But I can't seem to wrap my head around how it's valid. How can you assign the mp3Support variable to an empty string, then test to see if it's not equal to something all on the same line? I've never come across this before and it's puzzling me.

Upvotes: 1

Views: 149

Answers (3)

hvgotcodes
hvgotcodes

Reputation: 120198

mp3Support ends up being either true or false, as x != y returns true or false.

Same effect but shorter than writing

if(audio.canPlayType('audio/mpeg') !=  "") mp3Support = true;
else mp3Support = false;

Upvotes: 3

ajp15243
ajp15243

Reputation: 7952

The != operator is not an assignment operator, it is a comparison operator. So on the right-hand side of the = (which is always executed before the = operator assigns a value), the code is comparing audio.canPlayType('audio/mpeg')'s return value with an empty string. If the return value is the empty string (or any other falsey value, but you should read the comparison operator link above for details on that), then the right-hand side of the = statement evaluates to false. Otherwise the right-hand side will evaluate to true. The boolean value resulting from that comparison is then assigned to mp3Support.

Upvotes: 0

NoToast
NoToast

Reputation: 98

mp3Support = "" != audio.canPlayType('audio/mpeg');

can be written as

mp3Support = ("" != audio.canPlayType('audio/mpeg'));

And that last part returns either true or false.

Upvotes: 0

Related Questions