How come (23 == true) is incorrect but (!!23 == true) is correct? After all, there is === for exact comparisons

The question boils down to this: are both 23 and true truthy values? If so, shouldn't they be equal under the loose comparison operator ==? However, there is also the strict comparison operator === for cases where precise equality is required.

UPDATE: It seems we've concluded in the comments that it's a counterintuitive bug in the specification.

Answer №1

When dealing with type conversion, interesting comparisons arise. For instance, in the first scenario, the boolean value true is converted to the numeric value 1 before being compared to 23. Naturally, 1 != 23, even though both 1 and 23 can be interpreted as truthy values.

In another case, the expression !23 is first evaluated as false, which then becomes true when negated again with !false, resulting in true == true.

This situation showcases a peculiar aspect of type conversion where booleans are transformed into numerics, contrary to what one might expect.

Answer №2

When you compare a number to a boolean, the boolean is converted to the number 1.

Comparing x == y, where x and y are values, will result in either true or false. The comparison is carried out as follows:

  1. If the type of y is Boolean, the comparison x == ToNumber(y) is returned.

http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

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

What steps can I take to ensure the reset button in JavaScript functions properly?

Look at this code snippet: let animalSound = document.getElementById("animalSound"); Reset button functionality: let resetButton = document.querySelector("#reset"); When the reset button is clicked, my console displays null: resetButton.addEvent ...

Retrieve numerical values in inch format from a given string and output the greater value

Trying to extract size information from product names: Product A 30" Metalic Grey Product B 31.50" Led 54 watt Product C 40"-60" Dark Green The current code for fetching size information is: var product_name = $(this).text(); product_name.split('"& ...

Retrieving the value of an ASP.NET Literal in JavaScript

Is there a way to retrieve the value of an ASP.NET Literal control in JavaScript? I attempted the code below but it didn't return any values: var companyName = document.getElementById('litCompanyName').textContent; var companyNumber = docum ...

Guide to extracting the values associated with a specific key across all elements within an array of objects

My goal is to retrieve the values from the products collection by accessing cart.item for each index in order to obtain the current price of the product. const CartSchema = mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId, ...

Utilize JavaScript to activate a new browser tab and monitor its status for closure

When I attempt to open a new tab using JavaScript and track when it is closed, none of the events are being triggered. All the examples I found reference the onbeforeunload event for the current window, not for other window objects. window.addEventListe ...

Search a location database using the user's current coordinates

Currently, I am working on a project that involves a database containing locations specified by longitude and latitude. Upon loading the index page, my goal is to fetch the user's location and then identify every point within a certain distance radius ...

Recursive function in JavaScript with error handling using try-catch block

Within my nodejs script, I have implemented a system to generate dynamic tables and views based on the temperature data recorded for the day. On some occasions, the creation of these tables is hindered if the temperature falls outside of the normal range ...

Issues encountered during the installation of Electron JS

Having trouble installing electronjs in Node.js 18 LTS and NPM 10? Getting an error message like this? PS C:\Users\Administrator.GWNR71517\Desktop\electron> npm install electron --save-dev npm ERR! code 1 npm ERR! path C:\Users& ...

Accordion feature that loads JSON data dynamically with AJAX

I am facing a challenge with my HTML structure and corresponding CSS styling. The HTML code includes an accordion container with multiple sections that can be expanded or collapsed. <div class="accordion-container"> <ul class="accordion"> ...

Combine consecutive <p> tags within a <div> container

Can you group all adjacent <p> elements together within a <div> element? For example, assuming the following structure: <div class="content"> <p>one</p> <p>two</p> <h2> not p</h2> <p>thr ...

React Array Not Behaving Properly When Checkbox Unchecked and Item Removed

When using my React Table, I encountered an issue with checkboxes. Each time I check a box, I aim to add the corresponding Id to an empty array and remove it when unchecked. However, the current implementation is not functioning as expected. On the first c ...

The validation feature is ineffective when used with Material UI's text input component

I need a function that can validate input to make sure it is a number between 1 and 24. It should allow empty values, but not characters or special symbols. function handleNumberInput(e) { const re = /^[0-9\b]+$/; const isNumber = re.test(e.target.val ...

Upgrade Angular from 12 to the latest version 13

I recently attempted to upgrade my Angular project from version 12 to 13 Following the recommendations provided in this link, which outlines the official Angular update process, I made sure to make all the necessary changes. List of dependencies for my p ...

jquery disable document manipulation function

I need to make some updates to a simple function that involves the current textarea. $(document).on("keydown", updated_textarea_var, function (e) { // do stuff }); To achieve this, I tried disabling the previous function and running a new one w ...

I'm having trouble finding the issue in this straightforward code snippet. Can someone pinpoint the error for

(server-side) const express = require('express'); //setting up app instance const app = express(); //middleware const bodyParser = require('body-parser'); app.use(express.urlencoded({extended: false})); app.use(express.json()); //imple ...

What could have occurred if you reassigned setInterval to a variable within the useEffect hook?

Can multiple setInterval functions be defined repeatedly to the same variable in a React hook useEffect? After checking, I found that the variable has a new setInterval id value every time it is defined. However, I am curious if there are any instances re ...

Setting the value for a textbox using Jquery's .val() function works, while .attr() does not have the

//unable to get it working $("#TextBoxID1").attr("value","HI Value Change") //works perfectly fine $("#TextBoxID2").val("HI Value Change") <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <input type= ...

Encountering an error when attempting to iterate over an undefined property using an API

I am trying to fetch all classes and their assignments from Google Classroom. I successfully used Google's example code for listing the classes, but had to write my own code for listing the assignments. While the code runs as expected and lists the as ...

Why is the output [[]] instead of [] after removing the last array like [["1"]] using .splice()?

let array=[["1"]]; array[0].splice(0,1); // array = [[]] Why am I unable to make the sub-array blank when removing the last element? I want array = [] instead of [[]] after removing the last element from a sub-array. Check it out here: http://jsbin.com/ ...

AngularJS allows for the passing of a function value into another function

Is there a way for me to pass a value from one function to another? Here is an example of what I am trying to achieve: HTML <div> <li ng-repeat="language in languages" ng-click="myFirstFunction(firstValue) {{lang ...