When Should I Use The Double Exclamation Mark (!!) In JavaScript Compared To The Boolean() Function? Are There Any Advantages/disadvantages?

Asked 5 months ago
Answer 1
Viewed 79
0

If you've ever seen a double exclamation mark (!!) in someone's JavaScript code, you might be wondering what it is and what it's for. It's very simple: it's a quick way to convert a variable to a boolean value (true or false). Let me explain.

Using double exclamation points will immediately identify you as an overzealous surfer who doesn't know how to use plain English. (Unless you're writing JavaScript, in which case it doesn't matter.) Double exclamation marks or double explosions convert true or false values ​​to true or false. In other words, it acts like a Boolean (value).

The following values are considered by JavaScript to be falseys:

  • Empty string: ""
  • 0
  • null
  • undefined
  • NaN

The following values are considered by JavaScript to be truthys:

  • Object: {}
  • Array: []
  • Not empty string: "anything"
  • Number other than zero: 3.14
  • Date: new Date();

The JavaScript engine that executes the code tries to change (or coerce) the value. Boolean if needed, for example when evaluating an if statement.

JavaScript is a dynamic language, not a static language. This means that a variable can refer to or hold a value of any type, and that type can change at any time. You decide if you want a static or dynamic language.

The JavaScript engine that executes the code attempts to convert (or coerce) the value to a boolean when necessary, such as when it is evaluated in an if statement.

JavaScript is dynamic language, not static language. This means that a variable can refer to or hold a value of any type, and that type can change at any time. Whether you prefer a static or dynamic language is up to you.

However, you can definitely get an idea of ​​what JavaScript is like. Here's a quick list of the different JavaScript data types:

- Boolean

- String

- Number

- Object 

Convert object to boolean. If it is false (eg 0, null, undefined, etc.), then it is false; otherwise it will be true. The Boolean data type is the simplest of all data types because it is a single bit value: 0 (false) or 1 (true).
At that time ! It's not an operator, it's simple! operator twice.

I will explain how to detect IE version with a better example

let isIE8 = false;
isIE8 = !! navigator.userAgent.match(/MSIE 8.0/);
console.log(isIE8); // returns true or false

If you use below code

console.log(navigator.userAgent.match(/MSIE 8.0/));  // returns either an Array or null

Instead if you use !! result will be different

console.log(!!navigator.userAgent.match(/MSIE 8.0/));  // returns either true or false

Thank you for reading!

Read Also : Why did the Nets trade Mikal Bridges?
Answered 5 months ago White Clover   MarketsWhite Clover Markets