Why isn't the JavaScript if statement working properly when checking the length?

Below is an if statement that I have devised:

var TotalMoney=0;
var Orbs=0;
if (TotalMoney.length==2) {
Orbs+=1;
}

The intention behind this code snippet is to increase the value of "Orbs" by 1 when the digit length of "TotalMoney" equals 2. However, it's currently not functioning as expected. While troubleshooting, I realized that the issue lies within this code block itself. Although there are HTML and CSS elements tied to it, the problem persists. Any help in rectifying this would be greatly appreciated!

I stumbled upon another query while working with this code:

var totalMoney=0;
var orbs=0;
if (totalMoney.toString().length==2) {
orbs+=1;
}

This logic successfully identifies when the number has 2 digits, but now a new challenge arises. Whenever the number increments from 10 onwards (up to 99), it continuously adds an orb for each increment. My goal is for it to only add 1 orb when the number reaches double digits like 10 and then cease adding more orbs. Is there a way to achieve this desired behavior? Thank you in advance for your assistance!

Answer №1

TotalMoney is actually a numeric value, which means it doesn't possess the length property. If you want to determine the length of this number, you should convert it into a string first by using TotalMoney.toString().length.

Answer №2

The length property is not available for the Number object in JavaScript, so when you try to access TotalMoney.length, it will return undefined.

If you want to count the number of digits in TotalMoney, you can use the following code snippet:

if (TotalMoney.toString().length == 2) {
    Orbs+=1;
}

However, if TotalMoney is a negative number, like -1, then Orbs will still be incremented.

There might be a more efficient way to identify all 2-digit numbers, such as:

if (TotalMoney > 9 && TotalMoney < 100) {
    Orbs+=1;
}

Answer №3

TotalCash is a numeric value, to determine its length you can utilize the following code snippet.

TotalCash.toString().length;

Rather than using

TotalCash.length; 

You should update your code as demonstrated below:

var TotalCash=0;
var Gems=0;
if (TotalCash.toString().length==2) {
    Gems+=1;
}

Answer №4

The concept of length applies to arrays and strings specifically, not other types of variables.

If you need to count the number of digits, you can use:

if(TotalMoney>9)

Alternatively, you can convert the variable to a string and then check its length:

if(TotalMoney.toSting().length>2)

Answer №5

Below are some suggestions and general feedback on your code.

// It is recommended to start variable names with lowercase. For example, 'TotalMoney' 
// should be changed to 'totalMoney'.
var totalMoney=0; 

// Similarly, changing 'Orbs' to 'orbs' for consistency.
var orbs=0;

// Until you are more familiar with JavaScript, it's best to use '===' instead of '=='.
// This will help avoid common pitfalls.
if (totalMoney.toString().length === 2) {
orbs+=1;
}

Lastly, having a totalMoney value of 0 will not increment orbs by one. But if totalMoney is 10, as you mentioned, then orbs will increase accordingly.

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

Discover a method to receive an alert when the mouse exits the inner window along the y-axis

Is there a way to receive an alert if the mouse moves out of the inner window solely in the y-axis? Currently, alerts are triggered when the mouse moves out on both x-axis and y-axis. For example, if the mouse pointer hovers over the address bar coming fro ...

I'm trying to find a way to access a particular field within an HTML document using JavaScript in Node.js. Can anyone

<Response> <SMSMessageData> <Message>Delivered to 1/1 Total Cost: NGN 2.2000</Message> <Recipients> <Recipient> <number>+9109199282928</number> <cost>NGN 2.2000&l ...

How can I align the logo in the center of a ul

Many have attempted to resolve this issue, creating makeshift solutions or simply settling for an outcome that just "gets by." But what is the optimal approach? I have nearly finished something, yet for some reason, the logo isn't centered, rather the ...

Adding CSS files to a JSP page in Spring MVC

This is how my project's structure looks like: webapp: resources: css: test.css WEB-INF: pages: mvc-dispatcher-servlet.xml web.xml I am working on including a .css file in my jsp. mv ...

Utilize AngularJS to modify the appearance of text

Just starting out with AngularJS and I need to achieve the following task. I have a text that says "bob" and two buttons, one for bold and one for italic. When the bold button is clicked, I want to make the text BOB bold and when the italic button is click ...

What is another option for toggling in jQuery?

After deprecating the toggle method, I found a new way to toggle div: $("#syndicates_showmore").on("click", function () { if (!clicked) { $('#syndicates').fadeTo('slow', 0.3, function () { $(this).css( ...

What is the simplest method to transfer a variable from an HTML file to a Python script?

Can someone show me the simplest method to pass a variable from HTML to Python? I'm using the "input" tag to get the variable, and I only need to send it to my Python script without any response back to the HTML. Appreciate your help! ...

Javascript - Incorporate a hyperlink into my Flickr Api image query

I am struggling with incorporating a link around the image generated by this request due to my limited API knowledge. Below is the current function responsible for displaying the album images. To see a functional version, please refer to the provided fidd ...

Delete an <li> element upon clicking a span tag

I've been attempting to fadeOut some <li> elements, however I haven't had any success. Here's my code below: <li class="lclass" id="1"> First Li <span class="removeit" id="1" style="color:#C00;">Remove</span> ...

Looking to integrate the date, month, and year selection tags into the inline format

The Edit User Profile page includes a Birthday field, which is currently displayed vertically. I am looking to change the layout so that the Birthday field appears horizontally. Here is the code I am using: Within visitors/edit.html.erb, <%= simple_f ...

"Encountered an unexpected token in Javascript - jsp error

Recently, I started working on a JSP application and encountered an issue with passing URL variables from a servlet to a JSP page using request.getattribute. When trying to pass the data to a JavaScript function, we received the following error: Uncaught ...

What causes unescaped HTML characters to become unescaped when using $('div :not(script)').contents().filter(function()?

Developing a Chrome Extension that utilizes a click-to-call API, I have encountered an issue where certain pages are displaying unusual behavior. After investigating, I have identified this specific code snippet as the source of the problem. var rxpCtc = n ...

The CSS on the IIS 7 server is not functioning properly, unlike when it is on a

Upon debugging my ASP MCV 4 Application on Visual Studio 2012, I have encountered an issue with CSS not displaying properly after deploying it to IIS 7. It seems that some styles are missing in the live environment compared to how they appeared locally. I ...

Is there a way to extract an icon from an object or array?

Currently, I am facing challenges in extracting an icon from either an object or an array for a project I am working on. My approach involves storing the icon in a variable and passing it as a prop to another component. However, the functionality is not wo ...

Integrating jQuery Tooltip with Mouseover Event

I'm currently involved in creating a map of MIT projects for an architectural firm, and facing the challenge of maintaining the red dots mouseover state even when the mouse hovers over the tooltips that appear. Presently, the mouseover effect turns of ...

In Angular, what is the best way to update the quantity of an item in a Firestore database?

Whenever I attempt to modify the quantity of an item in the cart, the quantity does not update in the firestore database. Instead, the console shows an error message: TypeError: Cannot read properties of undefined (reading 'indexOf'). It seems li ...

Utilize Vue to access and read a file stored in the current directory

I am attempting to retrieve data from a text file that is located in the same directory as my .vue file. Unfortunately, I am encountering an issue where the content of the text file is not being displayed in both Chrome and Firefox. Instead, I am seeing th ...

Save property using the useState hook

I am working on implementing a sorting function in the child component, where the props are passed in from the parent through an axios call. Should I: Store the prop in the child component's useState? Pass the parent's setState function as a pro ...

Strategies for streamlining repetitive code within a closure in Angularjs

We are currently utilizing Angularjs 1x and I am in the process of refactoring some repetitive code within an Angularjs filter. However, I am facing challenges in getting it to function correctly. It should be a straightforward task. Our standard approach ...

The controller is providing a null response following an ajax Post request

I am having trouble with my ajax Post request targeting the edit action method in my controller. The issue is that none of the values are being populated, they all come back as null. What should be happening is that when the '.save-user' button ...