What does an operator or operator do in this JavaScript fragment?

So, I was looking through the jQuery source for the best programming tips, and I found some code where I am not sure what is going on.

type = type || callback; 

Can anyone explain what OR || does in variable assignment?

I did some experiments, set and set values, and what not, but I'm not wiser.

+4
source share
3 answers

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

Falsey values:

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

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

Consider this:

 var type = undefined; type = type || "default value"; 

As a result, the type variable will receive "default value" .

If it was like this:

 var type = "some value"; type = type || "default value"; 

Then it will save its "some value" .

+9
source

It sets the variable "type" to either its current value or the value of a "callback" if the current value is not "true". If "type" is undefined or null , or 0, or an empty string, or boolean false , then the callback value will be set.

change oops or NaN

+2
source

So, I see that several variables can be โ€œchainedโ€ together, and the first โ€œnon-falseโ€ value is assigned.

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

It's damn convenient.

0
source

Source: https://habr.com/ru/post/1337950/


All Articles