What's the double exclamation mark for in JavaScript?

 https://brianflove.com/2014-09-02/whats-the-double-exclamation-mark-for-in-javascript/


So, why double exclamation marks?

In some cases you may want to cast a variable to be explicitly boolean. Why? Well, the number one reason is that most of time developers do not use type safe comparison operators.

The type safe comparison operators are:

  • Strictly equal: ===
  • Strictly unequal: !==

When using the type safe comparison operators you are both checking that the values are equal (or unequal) and that their type is the same. Without the type safe comparison operators you are allowing the JavaScript engine the freedom to coerce your variables to true or false based on the truthy/falsey logic.

To cast your JavaScript variables to boolean, simply use two exclamation signs:

function() {
  var name = 'Brian';

  //alert 'string'
  window.alert(typeof name);

  //cast to boolean
  var bool = !!name;

  //alert 'boolean'
  window.alert(typeof bool);
}

In the example code above we are casting the string "Brian" to a boolean value. Therefore the second alert will indicate that the variable is now a boolean value.

Không có nhận xét nào:

Deactivate All Plugins When Not Able to Access WP-Admin

 https://www.wpbeginner.com/plugins/how-to-deactivate-all-plugins-when-not-able-to-access-wp-admin/ Method 1: Deactivate All WordPress Plugi...