Have you ever wondered why the expression `Number(new Boolean(false))` always returns `0

In the case of

Boolean(new Boolean(...)) === true
, it is because new Boolean(...) is treated as an object.

However, why does Number(new Boolean(false)) === 0 (+new Boolean(false) === 0) and Number(new Boolean(true)) === 1? Instead of resulting in NaN.

Why does the first example not involve unboxing, while the second one does?


*isNaN(Number({})) === true

Answer №2

The result of isNaN(Number({})) is true

Although this statement is accurate, it's important to note that an object and a Boolean object are not interchangeable.

To clarify, the Number function in JavaScript converts its argument into a numeric value following specific rules outlined in the ECMAScript standard. When dealing with objects, the conversion process is more complex than simply converting all objects to NaN (Not-a-Number). Consider the following examples:

const obj0 = {}

const obj1 = {
  toString() {
    return 1;
  }
}

const obj2 = {
  toString() {
    return 1;
  },
  valueOf() {
    return 2;
  }
}

const obj3 = {
  toString() {
    return 1;
  },
  valueOf() {
    return 2;
  },
  [Symbol.toPrimitive]() {
    return 3;
  }
}

const obj4 = Object.create(null);

console.log(Number(obj0)); //NaN
console.log(Number(obj1)); //1
console.log(Number(obj2)); //2
console.log(Number(obj3)); //3
console.log(Number(obj4)); //Error

As demonstrated, not all objects are equivalent when converted to a number. Some objects have distinct conversion behaviors.

When Number receives an object as an argument, it attempts to convert it to a primitive type, prioritizing numbers. The conversion process involves multiple steps:

  1. Determine the hint as "number".
  2. Check if the object has a @@toPrimitive method.
    • If available, call this method with the hint ("number").
  3. If no @@toPrimitive method exists, check for a valueOf method.
    • This step occurs because the hint is "number", making valueOf the first choice.
  4. If valueOf isn't found, search for a toString method.
    • Depending on the hint ("number" or "string"), either valueOf or toString will be used.
  5. If neither method is present, an error is raised.

After finding an appropriate method, execute it to obtain a numeric value.

At this point, we haven't discussed Boolean objects. This explanation pertains only to generic Number conversion. In summary, an object can be converted to a primitive number if it implements the necessary functionality.

Boolean objects do implement the required functionality through the valueOf method, which returns their boolean value:

const T1 = new Boolean(true);
const T2 = new Boolean(true);

console.log("T1.valueOf()", T1.valueOf());
console.log("typeof T1.valueOf()", typeof T1.valueOf());
console.log("T1 === T2", T1 === T2);
console.log("T1.valueOf() === T2.valueOf()", T1.valueOf() === T2.valueOf());

Hence, the equation Number(new Boolean(true)) equals

Number(new Boolean(true).valueOf())
, which simplifies to Number(true)

In general terms: Number(new Boolean(bool)) equals Number(bool)

Referencing the ToNumber conversion specification, true evaluates to 1, while false equates to 0. Therefore, Number(new Boolean(false)) === 0 since Number(false) is indeed 0. Similarly, Number(new Boolean(true)) === 1.

Answer №3

Boolean objects come equipped with a method called valueOf, which allows for customization of the primitive value during type conversions.

Boolean#valueOf() will return true when applied to new Boolean(true), and false when used with new Boolean(false).

This method is automatically invoked by both the Number function and the unary plus (+) operator, resulting in code like:

Number(true)

This would evaluate to 1, since the boolean value true translates to the numeric value of 1.


You can even define a custom valueOf function for any object to assign it a specific value. For example:

const object={
    valueOf(){
        return 10
    }
}
console.log(Number(object)) //10

Answer №4

When it comes to computing, true equates to 1

while false represents 0

0 is considered to be equivalent to false due to their shared zero elements in [semirings][Semiring on Wikipedia]. Despite being different data types, there exists an intuitive correlation between the two as they belong to isomorphic algebraic structures.

  • 0 acts as the additive identity and zero for multiplication. This property holds true for integers and rationals, however, it does not apply to IEEE-754 floating-point numbers: 0.0 * NaN = NaN and 0.0 * Infinity = NaN.

  • false serves as the identity for Boolean xor (⊻) and zero for Boolean and (∧). Representing Booleans as {0, 1}—integers modulo 2—one can perceive ⊻ as addition without carrying over and ∧ as multiplication.

  • "" and [] are identities for concatenation; nevertheless, they function as zeroes for various operations. While repetition falls into this category, both repetition and concatenation lack distributive properties, rendering them incompatible with semiring structures.

Implicit conversions, though handy in small-scale programs, may complicate reasoning in larger systems. This embodies just one of the multitude of compromises inherent in language design.

[Semiring on Wikipedia]: http://en.wikipedia.org/wiki/Semiring

quote from

read this

1 = false and 0 = true?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Remove an item from an array and keep it stored efficiently without generating unnecessary waste

I'm interested in finding a high-performance method for removing and storing elements from an array. My goal is to create an object pool that minimizes the need for garbage collection calls. Similar to how .pop() and .unshift() remove elements from a ...

Dynamic options can now be accessed and modified using newly computed getters and setters

When using Vuex with Vue components, handling static fields that are editable is easily done through computed properties: computed: { text: { get() { return ... }, set(value) { this.$store.commit... }, }, }, <input type ...

What is the best way to manage the loading and unloading of JavaScript within dynamically loaded partial pages?

Utilizing jQuery and history.js, I manage seamless transitions between partial pages to prevent entire document reloads. Some of these partial pages include unique javascript files. Despite successful page transitions, remnants of executed javascript linge ...

inSession variable in express: set to false

i keep receiving inSession:false when attempting to log in, it is expected to return true. I am utilizing express session, in combination with postges and sequalize. I have logged the state values and they are being rendered correctly, so they are n ...

Setting up server-side CORS in ExpressJS will not include the "Access-Control-Allow-Origin" header

Looking to tackle a CORS request for an ExpressJS server, which is new territory for me. Despite encountering similar issues in the past, I can't seem to pinpoint the problem this time around. It appears that the required headers may not be in the cor ...

Navigate to specific element from bootstrap navigation bar

I am in the process of creating a website for a small organization. The website is being constructed using bootstrap 4, and there is a navbar that connects to various flex-containers. I want these connections to smoothly scroll to their respective elements ...

Basic AngularJS application, however I am receiving {{this is supposed to be the information}}

Building an angularjs app I have set up an asp.net mvc4 application and integrated the angularjs package using nuget. The Layout.cshtml file has been updated to look like this: <!DOCTYPE html> <html ng-app="myApp"> <head> <meta ...

Is it possible to determine the number of JSON properties without the need for a loop?

I have a question about organizing data. I have a vast amount of data with various properties, and I am looking for a way to display each property along with how many times it occurs. For example: 0:[ variants:{ "color":"blue" "size":"3" } ] 1 ...

Creating a curved edge for a shape in React Native can add a stylish and

Issue Description I am working on an app and struggling with styling the bottom navigation bar. It's more complex than what I've done before, especially the curved top edge of the white section and the area between the blue/green circle and the ...

Node-express can seamlessly switch between multiple databases dynamically

After extensive searching for a solution to my problem, I have come up empty-handed. If anyone has experience in similar situations, your help would be greatly appreciated. I have developed an application server in Node Express with MySQL as the database. ...

Can someone please explain the distinction between $http.get() and axios.get() when used in vue.js?

I'm feeling a little bit puzzled trying to differentiate between $http.get() and axios.get(). I've searched through various sources but haven't found any answers that fully satisfy me. Can someone please offer some assistance? ...

Is there a way to use Javascript or JQuery to conceal all unchecked items in a RadioButtonList?

Currently, I am utilizing the Asp .net repeater to bind the selected value in the RadioButton list. Here is an example snippet: <asp:RadioButtonList ID="RadioButtonList1" runat="server" SelectedValue='<%# Eval("Numbers& ...

The parent element of a 3D div is causing issues with hovering and clicking on the child elements

In my scenario, the parent div is transformed in 3D with rotation, causing it to move to the backside. The issue arises with the child div containing a button that becomes unclickable due to the parent div position. Setting backface-visibility to hidden al ...

Tips for Avoiding "TypeError: fetch failed" on Next.js Page Server Component While Retrieving Data from Spring Boot API

Working on a Next.js application has been quite challenging as I fetch data from my Spring Boot API within a Page server component. Unfortunately, my GitHub Action CI/CD pipeline has been encountering failures during the Docker image build process, specifi ...

Unable to successfully interact with Paypal button using selenium automation

I'm facing an issue with Selenium where I am unable to click on the PayPal button. Despite trying various methods recommended in the Selenium documentation, the button remains unresponsive. I even attempted using the standard findElement method, but ...

Expanding Grid Container in Material UI to Fill Parent Height and Width

Challenge I'm struggling to figure out how to make a Grid container element expand to the height and width of its parent element without directly setting the dimensions using inline styles or utilizing the makeStyles/useStyles hook for styling. I&ap ...

When a cookie is set in NextJS with a static export, it reverts back to its original

My current project involves building a multilingual website. To handle language selection, I have implemented a system where the chosen language is stored in a cookie and retrieved using getInitialProps in the _app file, which is then passed as a context A ...

In order to locate a matching element within an array in a JSON file and update it, you can use Node

Good day, I have a script that updates the value in a JSON file const fsp = require('fs').promises; async function modifyNumberInFile() { try { let data = await fsp.readFile('example.json'); let obj = JSON.parse(dat ...

How can animations be disabled in Angular/Javascript?

I have been assigned the task of developing an Angular component for my company's applications that will include a toggle to disable all animations within the app for accessibility purposes. It is important to note that I am unable to go into each in ...

How to manually trigger the ajaxLoader feature in Tabulator version 3.5

Currently, I am working with version 3.5 of Tabulator from . When populating the table using an ajax request, a "loading icon" is displayed during the loading process. Prior to executing the ajax request for Tabulator, I perform some preliminary check op ...