What is the rationale behind the logic of the includes() feature in JavaScript?

I was exploring the includes() function and stumbled upon this interesting code snippet:

[NaN].includes(NaN) //Returns true

However,

NaN === NaN // Returns false

How can this discrepancy be explained?

Answer №1

When we compare NaN === NaN and use the includes method like [NaN].includes(NaN), we are essentially posing two distinct questions:

  1. Equality - are these entities with matching names truly equivalent?

The entity NaN is shapeless, denoting an absence of numeric value, making it impossible to conduct a direct comparison. The Equality operation adheres to the Strict Equality Comparison guidelines and asserts that any evaluation involving x === y where NaN features on either side will invariably yield false:

a. If x is NaN, return false.
b. If y is NaN, return false.

  1. Includes - does this array contain an item named as such?

Yet, in order to locate a NaN within an array while adhering to the Array#includes' requirement of a single parameter sans callback function, we must assign a "name" to our sought-after element. This necessity stems from the specification outlined in the ECMAScript 2016 (ECMA-262) documentation:

The includes method deviates from indexOf by employing the SameValueZero algorithm rather than Strict Equality Comparison, facilitating the identification of NaN array elements. Furthermore, it treats missing array elements as undefined instead of skipping over them.

The protocol delineated in SameValueZero(x, y) dictates that during comparison:

If both x and y resolve to NaN, the result is true.

Answer №3

[ NaN ].includes(NaN) This code snippet checks if the value NaN is present in the array [ ].

Both NaN === NaN and NaN == NaN will return false. The includes method simply verifies if a value exists within the array it is called on, possibly using the typeof() function under the hood.

typeof(NaN) // number
[ NaN ].includes(NaN) // true

typeof("1") // string
[ 1 ].includes("1") // false

typeof(1) // number
[ 1 ].includes(1) // true

This behavior follows the SameValueZero Algorithm defined for the includes method, where type checking is internally performed.

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

Deliver an extensive JSON reply through a Node.js Express API

When dealing with a controller in a node/express API that generates large data sets for reports, reaching sizes as big as 20Mb per request, maintaining a positive user experience becomes essential. What strategies can be employed to efficiently handle suc ...

How to Fix: jQuery UI Autocomplete Suggestions Remaining Open After Selection

I'm experiencing an unusual issue with a jQuery UI autocomplete feature. I have it set up so that when the text field is focused, a list of all options in the autocomplete appears. While this works as intended, selecting an item by clicking on it caus ...

Error: Socket.io.js is missing in the (node.js + express + socket.io) setup

I have been browsing through other similar answers like: node.js /socket.io/socket.io.js not found Socket.io not being served by Node.js server socket.io.js not found on client Configuring 'simplest' node.js + socket.IO + Express server Unfortun ...

route in mean stack isn't providing a response

I am having trouble creating a controller for /projects that should return all the data in the 'work' collection. The call is completing successfully with a status code of 200, but it is only returning an empty array or 'test:test' if u ...

What is the best way to retrieve the value of a specific textfield using the map function with a collection of

These posts have identical text fields for comments, using the same useState hook. I am trying to extract the value of a specific text field without affecting others. It's similar to Facebook posts, but I'm unsure how to achieve this. const PostT ...

Exploring jQuery Mobile: Uncovering the Power of clientX, clientY, and taphold Event

In my current project, I am implementing the taphold event and require the coordinates of the tapped point by the user. However, I have encountered an issue where event.clientX and event.clientY are returning as undefined (you can see the example here: her ...

JavaScript backspace function not functioning correctly

I'm having issues with the Backspace keycode not working. I've tested it in IE and Google Chrome, but it's not displaying anything in the console or the alert. Here is the code snippet: $(document).keypress(function(e) { con ...

Creating a personalized bullet text box with HTML and Javascript: A step-by-step guide

I have been working on creating a customized text box using HTML and JavaScript that has specific requirements: The text box should start with a single bullet point, like this: https://i.sstatic.net/U7pHo.png Each new line entered by the user should autom ...

What is the best method for caching inline SVG in web browsers?

Over the years, SVGs have remained popular due to their scalability. One key advantage of inline SVG is the ability to manipulate it with CSS and JS. Additionally, using the <use> tag allows for referencing the original element when repeating the sam ...

Trouble arises when attempting to incorporate the Restangular dependency with Angular using browserify

I've been using browserify to manage my angular dependencies successfully, however, when I try to add restangular I encounter an error: "Uncaught Error [$injector:modulerr]". Here's a glimpse of my package.json: "browser": { "angular": "./ ...

"Strategies for disabling navigation in a React single-page application when a user manually inputs a page href with React Router v6

Our application is built with Single Page Application (SPA) architecture and we utilize react router v6 for handling navigation. We have a scenario where each page has a specific set of restricted URLs which users should not be able to access directly by ...

Creating a function that uses setInterval to continuously update the input with a specific value

I am looking to use the setInterval function to continuously update the value of #test1. Additionally, I want the value of #test1 to be cleared and reset to 1 second after the user clicks a button. Example output can be found here: http://jsfiddle.net/eK ...

Exploring ways to reach a specific digit level in JavaScript

As a newcomer to JavaScript, I've been searching online and trying different solutions but none have worked for me. Currently, I have a variable called num = 71.666666666 I'm looking to limit this number to 71.66 So far, I have attempted the f ...

Animating an object in Three.js as it transitions smoothly between two different positions

If I have an object positioned at position.x = 0 and I wish to animate it smoothly to position.x = 2.435 in the render loop, how can I achieve this effect? ...

Adjusting the size of DIVs according to images retrieved dynamically from a database

I am currently in the process of building my online portfolio, and while I am new to JQuery and PHP, I am working through any challenges that come my way. However, I am facing a roadblock that has left me puzzled. My goal is to create a seamless iframe to ...

showing input using an array

I need some assistance with my JavaScript code. I have created three input boxes where users can add data, and then click a button to add the data into an array. The goal is to allow multiple users to input data and then display all values in the array alo ...

How to use jQuery to display only the following div with a matching class

I'm encountering an issue while attempting to perform a series of steps using jQuery. Unfortunately, I am unable to achieve the desired outcome. There are 3 steps, each with a class of .wiki-step- followed by a number. Here is my JavaScript code: fu ...

Unforeseen issue within Vuejs-nuxt (SSR Mode) is preventing the retrieval of the UserUUID through the getter in plugins, resulting in an unexpected '

In my vuejs-nuxt project using SSR mode, I encountered an issue when trying to call a socket event. I need to pass the userID to the socket from the store. The GetUserUUID getter functions properly in all other APIs except when called from the "plugin/sock ...

The feature "scrollTo" in mcustomscrollbar is not functional in Chrome, however, it functions properly in FireFox

It seems that there is an issue with the mcustomscrollbar "scrollTo" function not working in Chrome, although it works fine in FireFox. No errors are showing up in the console, so it appears to be a browser-specific problem. I even tested the functionali ...

What events occur before they are detectable in JavaScript?

Below is a code snippet for handling events related to an image: HTML <!DOCTYPE html> <html> <head> <title>Image Event Handling</title> </head> <body> <img src="someImagePath.jpg" class="img-1"/> &l ...