Table of Contents
Explicit forcing
Explicit cast using double NOT (!!) operator
grammar
Example
Use Boolean() constructor for explicit cast
Implicit coercion
Home Web Front-end JS Tutorial Explain non-boolean to boolean coercion in JavaScript?

Explain non-boolean to boolean coercion in JavaScript?

Sep 20, 2023 pm 09:37 PM

解释一下 JavaScript 中非布尔值到布尔值的强制转换?

We will learn about coercing non-Boolean values ​​to Boolean values ​​in JavaScript. For starters, the word cast is new in JavaScript. So, let’s clarify what coercion is.

Forcing is to convert a variable of one data type to another data type. As we all know, JavaScript is not a strictly typed language. Therefore, we don't need to define the type of the variable. Sometimes, JavaScript automatically coerces variables and gives unpredictable results in the output.

There are two types of casts in JavaScript. One is implicit coercion, and the other is explicit coercion. We will learn about both casts one by one in this tutorial.

Explicit forcing

An explicit cast occurs when a non-Boolean value is explicitly converted to a Boolean value using one of the Boolean coercion methods (such as Boolean() or !!).

We will discuss both methods in detail:

Explicit cast using double NOT (!!) operator

When we use not (!) operator on any value in JavaScript, it converts non-boolean value into boolean value.

One not(!) operator gives an error result for a value, and two not (!!) operators give an actual result for a boolean value.

grammar

Users can follow the following syntax to coerce non-Boolean values ​​into Boolean values ​​using the double NOT operator. -

var non_bool = "non-bool";
var bool = !!non_bool;
Copy after login

In the above syntax, the first not (!) operator coerces a non_bool variable of string type to a Boolean variable. The second not(!) operator is used to get the actual boolean value of the non_bool variable.

Here are some examples of using the double NOT operator -

console.log(!!0); // logs false
console.log(!!1); // logs true
Copy after login

In the above example, the non-Boolean value 0 is explicitly coerced to a Boolean value using the double NOT operator. The double NOT operator converts its operand to a Boolean value and then inverts it, so the expression !!0 is equivalent to !(!false), which evaluates to false.

Let’s see a complete example using HTML and JavaScript

Example

In this example, we create three numeric variables named num1, num2, and num3. Additionally, we initialized the numeric variables with different positive, negative, and zero values.

The user can observe the actual boolean value of the number in the output. The boolean value of zero is false because it is one of the false boolean values ​​in JavaScript.

<html>
<body>
   <h2> Coercion using <i> Doble NOT (!!) </i> Operator </h2>
   <p id = "output"> </p>
   <script>
      let output = document.getElementById("output");
      let num1 = 10;
      let num2 = 0;
      let num3 = -10;

      output.innerHTML += "num1 = " + num1 + "<br/>";
      output.innerHTML += "num2 = " + num2 + "<br/>";
      output.innerHTML += "num3 = " + num3 + "<br/>";
      output.innerHTML += "The boolean results of the above number values are given below.<br/>";

      // Using Double NOT Operator
      num1 = !!num1;
      num2 = !!num2;
      num3 = !!num3;

      output.innerHTML += "num1 = " + num1 + "<br/>";
      output.innerHTML += "num2 = " + num2 + "<br/>";
      output.innerHTML += "num3 = " + num3 + "<br/>";
   </script>
</body>
</html>
Copy after login

Use Boolean() constructor for explicit cast

In JavaScript, an explicit cast is when a JavaScript developer converts a variable from one data type to another. Here we will learn to explicitly cast a non-Boolean value to a Boolean value.

We can convert any value to a boolean simply using the "boolean" constructor in JavaScript.

grammar

Users can coerce non-Boolean values ​​in JavaScript to Boolean values ​​by following the following syntax.

let var1 = 30;
let var2 = Boolean(var1);
Copy after login

In the above syntax, var1 is a numeric data type and we cast it to a boolean value using the boolean constructor.

Here are some examples of using the Boolean() constructor -

console.log(Boolean(0)); // logs false
console.log(Boolean(1)); // logs true
Copy after login

In the above example, a Boolean function is used to explicitly coerce the non-Boolean value 0 to a Boolean value. A Boolean function returns the Boolean value of its argument, so the expression Boolean(0) returns false.

When we cast any non-boolean value to a boolean value except the six false values, it always gives a true result. For the six error values, we always get the wrong boolean value as the result.

Six fake boolean values ​​are given below.

  • mistake

  • “”

  • NaN

  • 0

  • null

  • Undefined

Example

We create different variables in this example and initialize them with different false values. We can observe that when we coerce them to boolean, it always gives a wrong boolean value.

<html>
<body>
   <h2> Coercion using the <i> Boolean()</i> Constructor </h2>
   <p id = "output"> </p>
   <script>
      let output = document.getElementById("output");
      // Creating the variables
      let falsy1 = undefined;
      let falsy2 = null;
      let falsy3 = "";

      output.innerHTML += "falsy1 = " + falsy1 + "<br/>";
      output.innerHTML += "falsy2 = " + falsy2 + "<br/>";
      output.innerHTML += "falsy3 = " + falsy3 + "<br/>";
      output.innerHTML +=
      "The boolean results of the above falsy values are given below.<br/>";

      // coercing the different falsy values to the boolean values.
      output.innerHTML += "falsy1 = " + Boolean(falsy1) + "<br/>";
      output.innerHTML += "falsy2 = " + Boolean(falsy2) + "<br/>";
      output.innerHTML += "falsy3 = " + Boolean(falsy3) + "<br/>";
   </script>
</body>
</html>
Copy after login

Implicit coercion

Implicit casts occur when a non-Boolean value is used in a context where a Boolean value is expected. In this case, JavaScript will automatically convert the value to a Boolean using a set of rules called "True" and "False".

Here are some examples of how to cast non-boolean values ​​to boolean values ​​-

Example

In this example, we use the hidden attribute of the image in JavaScript to display the image on click -

// Example 1: Implicit coercion in a conditional statement
if (0) {
   console.log("This will not be logged");
}

// Example 2: Implicit coercion using the logical NOT operator
console.log(!0); // logs true
console.log(!1); // logs false
Copy after login

In the first example, the value 0 is used in the conditional statement and is implicitly forced to be a boolean using the rules for true and false values. In JavaScript, the value 0 is considered false, so the conditional statement will not be executed.

In the second example, the logical NOT operator is used to negate a Boolean value that is not 0. The logical NOT operator inverts the Boolean value of its operand, so the expression !0 is equivalent to !false, which evaluates to true.

There are two types of casts in JavaScript. One is implicit coercion and the other is explicit coercion. We learned about both types of casts one by one in this tutorial.

The above is the detailed content of Explain non-boolean to boolean coercion in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles