Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 276
Craig552uk Avatar asked Dec 22 '22 18:12

Craig552uk


2 Answers

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".

like image 150
user113716 Avatar answered Jan 18 '23 23:01

user113716


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

like image 26
Pointy Avatar answered Jan 19 '23 00:01

Pointy