What could possibly be the reason for this not returning null?

Consider this JavaScript snippet:

var value = parseInt("");
console.log(value != Number.NaN ? value : null);

Why does the console output Nan instead of null?

Is there a way to modify the code so that it actually returns a null value?

I attempted to wrap the code in a function like this:

function parseIntOrDefault(value, def){
    var candidate = parseInt(value);
    if(candidate != Number.NaN) return candidate; else return def;    
}

console.log(parseIntOrDefault('', null));

However, the outcome remains unchanged.

For further context and demonstration of the issue, refer to this jsFiddle: http://jsfiddle.net/stevebeauge/BRP94/

Answer №1

It's recommended to utilize

isNaN(value);

for the purpose of confirming NaN

This is advised because:

console.log(NaN === NaN); // false!

NaN does not equal itself.

While it may seem counterintuitive, this behavior aligns with the characteristics of NaN.

Consider the following code snippet:

var a, b, c;
// a = 0;oops a is still undefined so we'll get NaN if we do an operation with it
b = 5;
c = 6
if (a + b === a + c) {
    console.log("math error?");
}

You wouldn't want to mistakenly believe that 5 === 6.

Answer №2

Ensure the variable "candidate" is a number, if not null then return it.

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

Flexbox Resizing Notification(?)

Recently, I've been utilizing flexbox in my layout design and it has been a game-changer. However, I am facing an issue that might be linked to my heavy use of AngularJS, particularly the ng-include feature. The specific problem arises when I incorpo ...

Is Python a suitable programming language for developing applications on a Raspberry Pi device?

I'm diving into the coding world for the first time and I have a project in mind - controlling my RC car with my smartphone using a Raspberry Pi 3. Research suggests that I should use Node.JS and JavaScript to create the app, but I'm wondering if ...

What could be causing this function to malfunction?

Apologies for any inaccuracies in technical terms used here. Despite being proficient in English, I learned programming in my native language. I am currently working on a project using the latest version of Angular along with Bootstrap. I'm unsure if ...

Manipulate a JavaScript object with AngularJS - viewing and editing capabilities

I'm looking to create a dynamic list of objects where clicking on an entry displays the object details and an edit button. When clicking on the edit button, the details should disappear and a form for editing the object should appear on the right side ...

What is the best way to access the second item using getByRole in React Testing Library when there is no specific name?

I am familiar with using the name option to select the first item here, but how can I go about selecting the second item if it does not have a name identified? -------------------------------------------------- button: Enter "Go": ...

Is Jquery not tallying up the numbers accurately?

Looking to secure a ticket with a complimentary offer? Here are the guidelines: A single individual can purchase 1 or more tickets, but the maximum is 4 An offer of at least 1 euro can be made for tickets, with no upper limit. For instance, if 4 tickets ...

Eliminating an SVG component from the webpage with the help of jQuery

Utilizing jQuery to insert an element into an embedded SVG can be achieved with the following code: var rect = SVG('rect'); $(rect).attr( { x: left, y: top, width: right - lef ...

How to efficiently send multiple objects in response to a single GET request with Express and Node.js

The code snippet I am working with looks like this - sendServer.get('/download',function(request,response){ var status="SELECT * from poetserver.download where status='0'"; console.log(status) connection.query(status,function(error,ro ...

merging pictures using angular 4

Is there a way in Angular to merge two images together, like combining images 1 and 2 to create image 3 as shown in this demonstration? View the demo image ...

What is the best way to show a dropdown menu list using my code and JSON response object?

I am currently working on displaying a dropdown list based on the JSON response object. How can I implement it with the code snippet below? in HTML <select class="form-control" name="productCategories[]" id="productCategories< ...

Adjust the height of a div using jQuery once the AJAX call retrieves the data

There is a div that always matches the height of the adjacent div, depending on the content loaded in it. This setup was functioning properly until I implemented a search feature using jQuery. Now, when I perform a search, the element used in the jQuery ca ...

Stop the background from scrolling and prevent auto-jumping to the top on mobile devices

When users click on the hamburger icon in the top right of our mobile site, I want the drop-down menu to appear and be scrollable without the background scrolling. I tried using JavaScript to set the body to fixed when the menu icon is clicked, but this ca ...

What is the best way to invoke a Javascript function within the same file using PHP?

I am facing an issue with my PHP file named "PhpCallJavascript". I am attempting to call the function CreateSVG() from within the PHP code. However, it seems that it is not working. Do I need to incorporate AJAX here? Or perhaps there is another solutio ...

After a period of running NodeJS and AngularJS together, I am encountering the net::ERR_CONNECTION_RESET error

My setup includes Express with NodeJS and AngularJS on the front-end. However, after performing a series of actions such as adding data, updating records, and showing a list, I encounter the error net::ERR_CONNECTION_RESET. Interestingly, this error only o ...

Angular.js controller unable to receive object array from $http.get in factory

I am fairly new to Angular development and I've hit a roadblock that's been holding me back for a while. My factory is successfully creating an array filled with objects, specifically RSS feed data, and I can see it loading in the console. Howev ...

Elevate the element from the choice API to the organization API using this.$parent

I recently developed a Vue 3 component called "Tab" using the option API. Here is the code: export default { name: "Tab", props: { name: {required: true}, iconClass: {required: true}, selected: {default: false} }, da ...

Which language should I focus on mastering in order to create a script for my Epson receipt printer? (Check out the manual for reference)

Printer Model: TM-T88V User Manual: Receipt-marker Web template for the printer: (Provided by Epson) I'm completely new to computer languages and have been trying to understand how to print receipts. I've researched XML, HTML, CSS, and Jav ...

Encountering an issue with the vue webpack-simple template: Uncaught TypeError - the intermediate value is not recognized as a function

Encountering a peculiar error while trying to create an IIFE method in the main.js file. Follow these steps to reproduce the issue, open the command prompt vue init webpack-simple test cd test npm install test npm run dev Open the main.js file and insert ...

What is the process for converting a file to base64 encoding, and then uploading it as a multipart file to a backend API using JavaScript

I am working on a project to create a micro-service that can receive base64 encoded data. However, when attempting to send more than 6 MB of data, I encountered the following error message: The multi-part request contains parameterized data (excluding ...

Entering credit card information in a modal popup using Bootstrap form

I have implemented a bootstrap modal for my credit card payment form and now I want to validate the credit card information. Currently, I am using basic validation in jQuery. <script> $(function() { $('#error_message_reg').text(""); //$( " ...