Programmer
Programmer

Reputation: 97

How does this JavaScript program works?

Sorry if this question is not upto the level of the site i cannot find help anywhere else. I have just started to learn JavaScript but i am stuck at an example code given in my text-book

var a = null;
function b() {return "B";}
(a || b)();
! "B"

There is not enough explanation given for the code and i am not able to figure out how does it work, can anyone help me please

Thanks

Akash

Upvotes: 1

Views: 61

Answers (3)

Ibrahim Najjar
Ibrahim Najjar

Reputation: 19423

I assume the source of your confusion comes from the third and fourth line.

Let's start with the third line: (a || b)();.

First a is evaluated and if it is not null or undefined then the result of this expression is a(), otherwise the result is b().

In your code snippet, a is null, so the expression is evaluated to b() which simply returns "B".

The OR || operator looks at its operands one by one, until it finds a value that is truthy and it returns it, if all the values are falsy then the last operand is returned.

For more information about truthy and falsy values, check here

Now this line ! "B", all strings in JavaScript are evaluated to true except for the empty string "", so the result of the previous expression is ! true so it is false.

Upvotes: 2

kviiri
kviiri

Reputation: 3302

There are two variables, a which is null and b which is a function that always returns the string "B". (a || b)() demonstrates a bit how logical && and || work in JavaScript - the evaluation is short-circuited and the last value evaluated is the value of the entire expression. Since a is null which is falsy, (a || b)() evaluates to b(), so you get the "B" print.

In general:

(a || b);  //a if a is truthy, otherwise b
(a && b);  //a if a is falsy, otherwise b

Falsy values are null, undefined, 0, the empty string "", NaN and of course false. Everything else is truthy.

Upvotes: 1

Pointy
Pointy

Reputation: 413712

The key is in how the || operator works. This line:

(a || b)();

is equivalent to this:

var f;
if (a)
  f = a;
else
  f = b;
f();

The || operator works by first evaluating the left side (in this case, a). It then checks to see whether that value is "truthy", which means that it's not null, 0, the empty string, and a couple other things. In this case it's clearly null, so it's not "truthy".

Thus the || operator goes on to evaluate the right side (in this case, b), and that value is taken as the result of the || operation. What's "b"? It's that little function that returns the string "B" when called.

Thus after the || operation is done, you're left with a reference to that function, and the subsequent () function call operator causes that function to be called.

Upvotes: 2

Related Questions