What causes the return of 'undefined' during the execution of type coercion?

Can you explain why the type of a variable changes but the value remains undefined when trying to set it?

let average; // Do I need to initialize with 'average = 0;' for it to work properly?
for (const [oddName, odd] of Object.entries(game.odds)) {
    // console.log(typeof oddName); // is a str
    console.log(typeof odd); // is a num
    console.log(typeof average);
    average += odd;
    // console.log(typeof average); // 'average' does change to a number
    console.log(average); //returns NaN
}

Answer №1

To further simplify this, let's see the impact:

let x;
console.log(x, " is of type ", typeof x);
x += 1;
console.log(x, " is of type ", typeof x);

let y = 0;
console.log(y, " is of type ", typeof y);
y += 1;
console.log(y, " is of type ", typeof y);

It's important to note that variable x starts as undefined since it was not assigned a value initially. When we add 0 to it, the type converts to "number", but adding one to an unknown value results in NaN.

On the other hand, assigning 0 to y makes it a number from the start. Adding one to zero gives us 1 as expected.

Answer №2

When you attempt to add a number with an undefined value, it results in NaN (Not a Number).

If you are looking for a solution, perhaps using the assignment operator (=) would be more suitable for your scenario.

https://i.sstatic.net/gEd9M.png

Answer №3

It is advisable to initialize the variable 'average' to 0 at the beginning of your code. This is important because when you add a number to an undefined value, the result is NaN (Not-a-Number).

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

Retrieve pixel information upon touch in an Appcelerator Titanium application on Android or iPhone

Can pixel level data of an image view be accessed using Titanium Mobile on Android/iPhone? ...

Unable to locate web element using Selenium in C#

Here is the HTML code I am currently using: <div class="modal-footer"> <button class="btn btn-primary" type="button" value="Show Alert" ng-click="questions.getIrMessage()" data-dismiss="modal">Confirm</button> <button class ...

Changing the event handler of a jQueryUI accordion dynamically from "click" to "mouseover" as needed

I am facing a scenario where I need to drag an item from a list and drop it into a target within an accordion. The challenge is that the target may be in a panel that is not currently open. To address this issue, I am looking to dynamically switch the acc ...

Transforming a Shadertoy experiment into a customized Three.js playground on my local machine

I am currently working on a local shader sandbox project inspired by a Shadertoy created by lennyjpg. I have been referencing two Stack Overflow questions and answers (one, two) for help. The goal is to convert the Shadertoy code to use Three.js for a larg ...

If the Ajax request is successful, scroll to the bottom of a Div using jQuery

An interesting scenario arises with this Div that contains user messages, where the newest message always appears at the bottom of the Div and triggers a scroll bar if the message count exceeds the height of the div: <div class="list-group-message" s ...

The occurrence of the error "Failed to resolve component" in Vue 3.0.11 seems to be random, particularly when using recursive components

After thoroughly checking all similar questions on this platform, I did not find any relevant solutions. In most cases, the error seems to occur when utilizing components:[comp1,comp2] This is incorrect because the components property should be an object. ...

Adding a personalized service into a separate service within Angular 2

I am having trouble injecting my own service into another service. While I can inject standard Angular services like Http without any issues, attempting to inject custom services results in an exception. For example, here is how MyService is set up: impo ...

Currently dealing with a script that utilizes AJAX GET to incorporate JSON data into my table

Greetings and thank you for taking the time to read this! Within my HTML, I have implemented a form element that allows inputting data into 5 different fields. This data is then transmitted to a database using my unique API key. Once stored in the database ...

Selecting a directive's scope

Though the title may not capture it quite accurately, I struggled to find a more fitting description. I crafted a directive that incorporates an ng-repeat: app.directive('appDirective', function($purr){ var template = '' + ...

Trigger SocketIO message when the page is closed or when the user confirms leaving the page with on

My server application is responsible for executing firmware updates on remote devices using radio communication. Occasionally, the update process may drag on indefinitely due to disruptions in the radio network. If this happens, users might want to interr ...

JavaScript query: Why does code return NULL in Internet Explorer but functions correctly in FireFox?

In my external .js file, I have successfully linked this function... function SubmitAge(age, UpdatePanelID, HiddenAgeID) { $get(HiddenAgeID).value = age; __doPostBack(UpdatePanelID); } I am triggering it from an onClick event of an a href="#" tag. ...

Using JavaScript to set the value of an input text field in HTML is not functioning as expected

I am a beginner in the programming world and I am facing a minor issue My challenge lies with a form called "fr" that has an input text box labeled "in" and a variable "n" holding the value of "my text". Below is the code snippet: <html> <head&g ...

What is the best way to retrieve the returned value from a jQuery GET call?

I was looking to implement something along these lines: function example(); var result = example(); if(result == 1) However, in my example function, I am making a Get request and using a callback that is not returning the value correctly as the ...

How can one generate an array containing all attributes found in the HTML of a website?

I have a project idea where I want to be able to input a hyperlink address and then get a list of attribute contents as the output. For instance, if I input a Netflix genre hyperlink for Adventure Movies, I'd like to receive a list with all the movie ...

reveal concealed section and seamlessly glide to specified location inside the secret compartment

I have implemented a feature on my website where hidden divs are revealed one at a time, with the screen scrolling to display each specific div. While this code functions well, I am now looking to enhance it by opening the hidden div and smoothly scrolling ...

Switching the background image when hovering over a list element

Looking at the screenshot, it's clear that there is an unordered list with a background image set on the div. What I am trying to achieve is to have the background image change whenever I hover over a list item. Each list item should trigger a differe ...

Stopping the Game Loop in Windows Phone 8.1 with WinJS

Despite everything working smoothly, I am facing an issue with stopping the game loop when the Start button is pressed and the app is moved to the background. The event handler for suspend, app.oncheckpoint = function(args) {}, does not seem to fire for t ...

Can the loading of the window be postponed?

I've created a script that displays a message when the user first visits the website. The message then fades out, followed by another section fading in after a short delay. $(window).load(function() { $(".greeting").delay(1500).fadeOut("500"); ...

Step-by-step guide for serving static JavaScript files using NextJS

I am currently exploring the process of hosting static js and css files using NextJS. My journey began with creating a react app through create-react-app, where I developed an App component before executing the npm run build command. This resulted in the ...

Encountering the React Native error message "TypeError: Object(...) is not a function" while using react navigation stack

I am currently facing an issue with my react-navigation-stack. My suspicion lies in the dependencies, but I am uncertain whether that is the root cause. The objective at hand is to create a text redirecting to another page. If there is any irrelevant code, ...