0

I was wondering what the following code does in terms of the = and then the OR operation || arrangement. I've seen it around heaps but never understood what its doing exactly. I get that its probably assigning one OR the other property depending on whichever is available, but how does it determine that? does it look for which one is not "undefined"? does it only use the second one if the first is "undefined"? can you have more then one "||"? what if both aren't "undefined"? what if both are "undefined"?

the audio context code is just where i have seen it most recently.. im not concerned about how that works, rather im concerned about the arrangement of the operators and how they work.

I also understand this has probably been addressed somewhere else but i couldn't find it because i dont know what this arraignment is called, does it even have a name?

window.AudioContext = window.AudioContext||window.webkitAudioContext;
  • 1
    `window.AudioContext||window.webkitAudioContext` --- can you understand what this expression returns? – zerkms Oct 22 '15 at 23:44
  • It is making the value of `window.AudioContext` cross browser compatible saying do `this` or || `that` depending on what browser you are in – Adam Buchanan Smith Oct 22 '15 at 23:53
  • Related: [this question](http://stackoverflow.com/questions/476436/is-there-a-null-coalescing-operator-in-javascript) and its answers. – James Oct 22 '15 at 23:55

2 Answers2

1

I've always heard of this referred to as a sort of feature detection pattern. Basically in the case of:

var a = x || y;

if x is not undefined or null, a will be assigned x. Otherwise it will be assigned y. You can chain them as well. JS picks the first one that isn't null or undefined.

var b = null || undefined || "s"; // b will be "s"

This is handy if you are trying to polyfill a function in older browsers, or if you just want to make sure that you aren't overwriting an existing function with the same name in the current namespace. You can achieve similar results with the typeof operator or the ? operator as well.

el_n8
  • 88
  • 7
0

OR (||) will return the first truthy expression it encounters, so this pattern is used to provide a default value if another value is falsey (such as undefined, null, 0, false or an empty string ""). In this case it is providing the webkit specific implementation of audioContext if the standard implementation is not available.

devitall
  • 56
  • 1
  • 4