JavaScript is displaying Not a Number (NaN) instead of the expected value

Currently, I am facing an issue with retrieving the user's work duration from a database column stored in minutes. My goal is to convert this value to HH:mm format to calculate the total hours worked per week, but I'm encountering obstacles.

<td><strong>{{ Math.floor(teamUniqueHoursTotalPerUser[entry] / 1000 / 60 / 60) + 'h ' + Math.round(teamUniqueHoursTotalPerUser[entry] / 1000 / 60 % 60) + 'm' }}</strong></td>

I struggle with math, so my aim is to tackle this task using only Math libraries to enhance my skills. Currently, when there is no value present, I receive a NaN error. Instead, I would like it to display as Total: 0h 0m when no value exists.

Within the controller:

$scope.teamTimeInfoForCurrentWeek = {};

if (data != null) {

    var uniqueNamesArray = [];
    var uniqueHoursWorkedCurrentWeekPerUser = {};

    for (i = 0; i < data.length; i++) {
        var newUser = 0;
        data[i].Full_Name = data[i].Employee_Last_Name + ', ' + data[i].Employee_First_Name;

        if (uniqueNamesArray.indexOf(data[i].Full_Name) == -1) {
            uniqueNamesArray.push(data[i].Full_Name);
            newUser = 1;
        }

        if (data[i].Hours_Worked !== null && data[i].Hours_Worked >= 0) {

            data[i].Hours_Worked = moment.duration(data[i].Hours_Worked, 'minutes');
            if (newUser == 1) {
                uniqueHoursWorkedCurrentWeekPerUser[data[i].Full_Name] = moment.duration(data[i].Hours_Worked, 'minutes');
            }
            else {
                uniqueHoursWorkedCurrentWeekPerUser[data[i].Full_Name] += moment.duration(data[i].Hours_Worked, 'minutes');
            }
        }

        if (data[i].Lunch_Duration !== null && data[i].Lunch_Duration >= 0) {
            data[i].Lunch_Duration = moment.duration(data[i].Lunch_Duration, 'minutes');
        }
    }
    $scope.teamTimeInfoForCurrentWeek = data;
    $scope.teamHoursWorkedForCurrentWeek = uniqueHoursWorkedCurrentWeekPerUser;
    $scope.teamNameInfoForCurrentWeek = uniqueNamesArray;

Despite attempting to incorporate moment.js, I encountered difficulties with values exceeding 24 hours when trying to create a moment duration (minuteValue, 'minutes').

Any assistance provided would be greatly appreciated. JavaScript remains a challenging area for me.

Answer №1

If a value is missing, it will be identified as undefined. When using math operations on something that is undefined, the result will be NaN (Not-a-Number). To ensure that any variable that could potentially be undefined instead defaults to 0 when performing math operations, you can utilize the || operator in-line.

For example:

Math.floor((teamUniqueHoursTotalPerUser[entry] || 0) / 1000 / 60 / 60)

Answer №2

When attempting to perform mathematical operations on a non-numeric value, you will receive the result of NaN. It appears that the variable

teamUniqueHoursTotalPerUser[entry]
is not defined in your code, leading to it being interpreted as undefined. Dividing undefined by any value will always yield NaN.

Answer №3

When looping through data, it's important to handle default values for variables. In this case, if an employee's first name is missing, the comma is removed from the output.

Similarly, if Hours_Worked is missing, it defaults to 0.

for (i = 0; i < data.length; i++) {
    var newUser = 0;
    data[i].Full_Name = (data[i].Employee_Last_Name || '') + (data[i].Employee_First_Name ?  ', ' + data[i].Employee_First_Name : '');
    data[i].Hours_Worked = data[i].Hours_Worked || 0;

    ...
    ...
}

Answer №4

When converting a value to a number, it is possible for it to result in NaN. There are various scenarios where this can occur as outlined in the documentation found at https://www.example.com/jsref/jsref_isnan.asp

isNaN(123) //false

isNaN(-1.23) //false

isNaN(5-2) //false

isNaN(0) //false

isNaN('123') //false

isNaN('Hello') //true

isNaN('2005/12/12') //true

isNaN('') //false

isNaN(true) //false

isNaN(undefined) //true

isNaN('NaN') //true

isNaN(NaN) //true

isNaN(0 / 0) //true

It is important to address any potential cases of NaN before attempting to convert the value to a number for

teamUniqueHoursTotalPerUser[entry]
.

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

Controller unable to update AngularJS view

As the title suggests... I'm facing a challenge with this code snippet: (function(angular) { 'use strict'; angular.module('app', []) .controller('ctrl', ['$scope', function($scope) { $scope.ini ...

Make sure to wait for the current operation to finish before moving onto the next one

In the primeData function within the datacontext, four queries are made to a back-end Web API service: function primeData(forceRefresh) { return (getLookups(forceRefresh) // this needs to complete before moving on .then(success)) ...

PHP and AJAX allow for seamless data retrieval without the need for page refreshing, and the data can be easily displayed in a modal window

I am currently encountering an issue with sending data to another page without refreshing. I am able to send the data as text, but for some reason, I am unable to send it as a modal. Why might this be happening? Here is an image of my current page https:/ ...

definition of a function with another function

I'm curious about whether it's considered a good practice in JavaScript to define a function within another function. Take a look at this code snippet: module.exports = function() { function foo() { // do something } ... foo() .. ...

An effective way to confirm a notify.js alert using selenium

I am trying to validate the text of a notification message with the following code structure: <div class="notifyjs-corner" style="top: 0px; left: 45%;"> <div class="notifyjs-wrapper notifyjs-hidable"> <div class="notifyjs-arrow" styl ...

Exploring the power of Javascript for number lookup

I am currently working on a coding project using TypeScript and JavaScript to locate a specific number provided by the user within a list. The goal is to display whether or not the number is present in the list when the 'search' button is pressed ...

The silent button malfunctioning - Ionic

Within the html file: <video preload="metadata" muted="true" controls playsinline webkit-playsinline loop> Despite the "muted" tag, the video is playing with sound in both the browser and on the device. After referencing the video and setting the ...

What is the proper way to request permission for allowing others to access the mailto function?

I want to create a feature where users can open email on click using JavaScript. However, I have encountered an issue with using the mailto function in Chrome, as it requires changing the handlers settings to make it work. My query is whether it is possib ...

Karaf (Predix 14.3) error encountered: 413 FULL head - 413 (Request Entity Too Large) - Please check the request size

My current architecture setup looks like this: BROWSER <-> Play Framework 2.2.1 + AngularJS <-(REST)-> Karaf Everything is working fine in this configuration. However, when I introduce: BROWSER <-> Apache Reverse Proxy <->Play Fr ...

Unable to utilize the "let" keyword in WebStorm

Currently, I am delving into learning typescript and attempting to create a simple 'let' statement. However, I encountered an error indicating the need to use ECMAScript 6 or later versions. The exact message from the typescript compiler states: ...

"Unlocking the Power of jQuery: A Guide to Accessing XML Child

I'm struggling to extract the xml in its current format. While I can easily retrieve the InventoryResponse, I am facing difficulties when trying to access the child node a:Cost. Despite conducting research, I have been unable to find a solution that w ...

a guide on integrating dynamic text input in AngularJS with SVG circles created in D3.js for effective filtering

I am working with a d3js bubble chart that contains multiple circles, each identified by an id corresponding to a city name. var cities = ["Toronto", "London", "Paris"]; In addition, there is a standard input box in the HTML code. <input id="searchBo ...

Jest - experiencing intermittent test failures on initial run, yet succeeding on subsequent runs

Writing tests with jest and supertest npm on a node server has been a challenge for me. When I try to run all the tests together, some of them fail inexplicably: https://i.sstatic.net/TWDVp.png However, if I selectively run only the failed tests in the t ...

Trigger an alert message upon loading the HTML page with search text

I need to search for specific text on a webpage and receive an alert if the text is found. <script type='text/javascript'> window.onload = function() { if ((document.documentElement.textContent || document.documentElement.innerText ...

Successfully updating a document with Mongoose findByIdAndUpdate results in an error being returned

findByIdAndUpdate() function in my code successfully updates a document, but unexpectedly returns an error that I am having trouble understanding. Below is the schema that I am working with: const userSchema = mongoose.Schema({ phone: String, pas ...

From where does the require.js file originate?

Currently, I am learning Angular 2 from the tutorial available at https://github.com/pkaul/maven-typescript-example. Once I proceed with the 3rd step (mvn jetty:run), a runnable war folder is generated in the example-webapp/target directory. However, I ha ...

Discovering an item within an array of objects using the find method in Ajax

Within my backend PHP code, I iteratively define the following: foreach ( $data as $res ){ $approved[ ] = [ 'id' => $count, 'title' => "some title" ]; $count++;$title=... ) This eventually leads to the creation ...

How can union types be used correctly in a generic functional component when type 'U' is not assignable to type 'T'?

I've been researching this issue online and have found a few similar cases, but the concept of Generic convolution is causing confusion in each example. I have tried various solutions, with the most promising one being using Omit which I thought would ...

Invoke a jQuery method in a dynamic manner

Is it possible to achieve the following? var todo = "text"; $this.eval(todo).split(/\b[\s,\.-:;]*/).length; The desired function is: $this.text().split(/\b[\s,\.-:;]*/).length; I'm struggling to find a solution... Ca ...

The jQuery toggle function seems to be skipping alternate items

I have recently started learning Javascript and JQuery. Currently, I am working on creating a comment system where you can click reply to display the form. However, I'm facing an issue where the form only shows up for the first comment reply, not for ...