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

Looking to retrieve the text content of an element using jQuery?

My goal is to use jQuery mobile to transfer a user to a linked page when they click on an <li> element, and then display an alert with the text of the list element they clicked. However, my current implementation only shows an empty alert box. < ...

What is the syntax for accessing a nested object within the .find method?

Currently building an application in node.js. I am struggling with referencing the "email" element in the "userData" object within the Order model when using the find method. Any suggestions on how to properly refer to it? Order model: const orderSchema = ...

Create a class for the grandparent element

Is there a way to dynamically add a class to a dropdown menu item when a specific child element is clicked? Here's the HTML structure I have: <ul id="FirstLevel"> <li><a href="#">FirstLevel</a></li> <li>< ...

JavaScript HTML content manipulation

Why doesn't this code work? innerHTML cannot handle something so complex? <html> <head> <script type="text/javascript"> function addTable() { var html = "<table><tr><td><label for="na ...

A guide to monitoring and managing errors in the react-admin dataProvider

Rollbar has been successfully integrated into my react-admin app to track uncaught errors. However, I've noticed that errors thrown by the dataProvider are not being sent to Rollbar. It seems like errors from the dataProvider are internally handled w ...

The messageReactionAdd event has suddenly stopped functioning without any explanation

Currently, I am developing a Discord bot that assigns the role "Voteur" to a user when they react to an embed message created by the bot. Everything was functioning perfectly until recently, but for some reason, it has stopped working. The bot successfull ...

jQuery will envelop the HTML elements in an inconsequential div

Imagine a website that is visually complex, with various styles and images positioned in different ways. What if we wanted to add a small overlay icon above each image? At first, the solution might seem simple - just use absolute positioning for a span el ...

next.js experiencing hydration issue due to using div tag instead of main tag

I've come across an issue with hydration in NextJS and after debugging, I discovered that using the div tag instead of the main tag is causing this problem. The error message I'm receiving Here is the code snippet that triggered the error impo ...

Can the function be executed without the need for ng-app?

After researching my AngularJS application, I discovered that having 2 ng-app tags in the html file means only the first one will be executed. In my code snippet below <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"> ...

Utilizing React Recharts to create personalized tooltips

In my current project, I am looking to create a custom tooltip to replace the default one in recharts. The default tooltip that I want to change is shown below: https://i.stack.imgur.com/TjTiL.png I would like the new custom tooltip to look like this: ...

Innovative sound system powered by React

I am working on implementing a music player feature on a website where users can select a song and have it play automatically. The challenge I am facing is with the play/pause button functionality. I have created all the necessary components, but there see ...

In JavaScript, alert a message once all images have been clicked

I'm encountering a small issue with my javascript code. I am developing a game for a school project where the objective is to click (remove) fish using a fishing rod. However, the game does not have an end condition set up, so players cannot win. Belo ...

Obtain the URL of the parent window from a modal dialog using JavaScript

What is the proper syntax for obtaining the URL (specifically, the PATH) of the parent window from a modal dialog box in Internet Explorer. I have attempted several variations such as: window.opener.document.location window.opener.location this.opener.do ...

Extracting JSON data within ajax's success callback

I am currently working on parsing and displaying JSON data that is returned from a server. To accomplish this, I have set up an AJAX call that reads user input, sends it to a PHP page via POST method, and the PHP page var_dumps the array containing the JSO ...

ReactJS error: Unable to access the setState property

As a newcomer to ReactJS, I have been facing some challenges. I recently familiarized myself with the ES6 syntax, and it claims that the following pieces of code are equivalent in meaning. 1. YTSearch({key: API_KEY, term: 'nba'}, function(vide ...

Efficiently managing modules with requirejs and Backbone.Marionette

After organizing the file structure of my web app, utilizing RequireJs and Backbone.Marionette, it now looks like this: |- main.js |- app.js |- /subapp1 |- subapp1.js |- subapp1.router.js |- /subapp2 |- subapp2.js | ...

Using assert along with exceptions in code can provide additional error handling capabilities

I recently began using Protractor in combination with Mocha and Chai. I've reached a point where I have performed some asserts like: const attributes = await TestingModal.getButtonAttributes(driver, myCss) assert.equal(attributes.text, 'Tes ...

What makes AJAX take so much time to load?

Hey everyone, I’ve been working on compiling and sending some forms to a PHP file but I've been noticing that the process is quite slow. Even when I use var_dump in PHP to only display the POST values, it still takes a considerable amount of time co ...

What is the process for recording information using a static method in TypeScript within a class?

For my school project, I'm struggling to retrieve the names from a class using a method. One class creates monsters and another extends it. abstract class genMonster { constructor( public id: string, public name: string, public weaknesse ...

What is the best way to connect to my shop through RTK-Query API?

Is there a way to access my redux-toolkit store data from within the rtk-query endpoints? How can I retrieve information from my store in the query or transformResponse methods? import { createApi } from '@reduxjs/toolkit/query/react' import cus ...