Best practice: Truthy and falsy values in JavaScript

The following example shows how the types of functions and objects can be used to detect the capability of a web browser. The example shows the detection of the WebRTC functionality in a standard way and then uses the ternary operator and the behaviour of truthy and falsy values to refactor the code. The business logic is written in a self-executing function.

Starting point

(function() {
  window.browser = {
    supports: {
      WebRTC: false
    }
  };
 
  navigator.getUserMedia = (navigator.mozGetUserMedia || navigator.webkitGetUserMedia);
 
  if (navigator.getUserMedia !== undefined) {
    window.browser.supports.WebRTC = true;
  } else {
    window.browser.supports.WebRTC = false;
  }
})();

With ternary operator

(function() {
  window.browser = {
    supports: {
      WebRTC: false
    }
  };
 
  navigator.getUserMedia = (navigator.mozGetUserMedia || navigator.webkitGetUserMedia);
  window.browser.supports.WebRTC = (navigator.getUserMedia) ? true : false;
})();

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.