Craig552uk
Craig552uk

Reputation: 681

What does the or operator do in this bit of JavaScript?

So I was browsing the JQuery source for better programming tips, and I found a bit of code where I'm not sure what's going on.

type = type || callback;

Can anyone explain what the OR || is doing in the variable assignment?

I did a few experiments, setting and un-setting values and what-not, but I'm none the wiser.

Upvotes: 4

Views: 84

Answers (3)

Craig552uk
Craig552uk

Reputation: 681

So I see multiple variables can be 'chained' together and the first "non-falsey" value is assigned.

var val, a, b, c;
a = undefined;
b = null;
c = "C";
val = a || b || c;
alert(val);

That's pretty damn handy.

Upvotes: 0

user113716
user113716

Reputation: 322492

If type is a "falsey" value, then the value of callback will be assigned to the type variable, otherwise type will be assigned.

The "falsey" values are:

  • false
  • null
  • undefined
  • 0
  • "" (empty string)
  • NaN

So basically it says "replace type with callback if type is any one of the falsey values".

Consider this:

var type = undefined;

type = type || "default value";

The type variable will ultimately get "default value" assigned.

If it was like this:

var type = "some value";

type = type || "default value";

Then it would keep its "some value".

Upvotes: 9

Pointy
Pointy

Reputation: 413717

It sets the variable "type" to either its current value, or the value of "callback" if the current value is not "truthy". If "type" is undefined, or null, or 0, or the empty string, or boolean false, then it'll be set to the value of "callback".

edit oops or NaN

Upvotes: 2

Related Questions