When attempting to throw and catch errors, the outcome was not as anticipated

I've encountered an issue with the try, catch, and throw in my code. The outcome I'm seeing is not what I expected. Here's the problem: when I enter a number greater than 5 into the form field, nothing is displayed instead of "too high." But when I enter numbers less than 5, it shows "too high" instead of "too low." Additionally, most of the other if conditions don't seem to be working as intended except for empty and too high. Can anyone shed light on this anomaly?

function myFunction() {
  var x, message;

  message = document.getElementById('para');
  message.innerHTML =  '';
  x = document.getElementById('formField').value;

  try {
    if (x == "") throw 'empty';

    if (isNaN(x)) throw 'not a number';

    x = Number(x);

    if (x < 5) throw 'too low';

    if (x > 5) throw  'too high';

  }
    catch(err){
    message.innerHTML = 'input is ' + err;
  }
}

It seems like many people are struggling to grasp my issue here. This code was directly copied from W3schools, but it's not functioning correctly. The various if statements are meant to trigger specific errors when the input value meets certain conditions. However, they are producing unexpected results. For example, entering just 2 triggers "input is too high" instead of "too low." Entering numbers above 5 doesn't trigger any error, and there is no response from JavaScript for NaN.

If anyone can comprehend what I'm trying to convey, please run the code yourselves and help me understand where I might be mistaken.

Answer №1

Debugging in the console can be quite helpful:

NaN === NaN

It may leave you wondering why. Another thing to keep in mind is that when working with variables like x, it's important to convert them to integers:

x = parseInt(document.getElementById('formField').value);

Answer №2

It is recommended to utilize the isNan() function instead of Nan for checking if a value is not a number. You can refer to an example here...

For further explanation, you can visit this link: Why Is IsNaN(x) different from x == NaN where x = NaN

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

Setting default date and time for Bootstrap datetimepicker only in the expanded calendar view

Here is the setup: $(function () { $('#datetimepicker').datetimepicker({ defaultDate: moment(), sideBySide: true }); }); This configuration allows setting a default date & time when no value is provided for the f ...

Meteor: Transmitting Session data from the client to the server

Below is the code snippet I am utilizing on the client side to establish the Session variable: Template.download.events({ 'click button': function() { var clientid=Random.id(); UserSession.set("songsearcher", clientid); ...

Steps to remove information from a database using PHP, AJAX, and vanilla JavaScript (without jQuery)

I am facing an issue with deleting data from my database. Whenever I click on the delete button, it deletes the first row instead of the intended row. Below is my PHP code: <?php $connect = mysqli_connect("localhost","root","","abu"); if($conne ...

Tips for effectively crafting a component capable of managing both a value and an observable for that specific value

I'm actually curious about two things. When is it appropriate to pass an observable of an object into a component versus resolving it with the | async method? If I want to create a versatile reusable component that can handle both scenarios - accept ...

Managing server JSON objects in Adobe AIR

I am facing an issue with a script that fetches objects from a remote server using an Ajax call. The server sends back objects in JSON format. However, while working on Adobe AIR, I encountered a restriction on utilizing eval() due to security concerns. As ...

JavaScript challenge at an electronics store coding competition

Hello, I recently attempted a code challenge but unfortunately only passed 9 out of the 16 tests. I am seeking feedback on what may be going wrong in my code. The problem link can be found here: function getMoneySpent(keyboards, drives, budget) { l ...

Change from one value to another using a decaying sinusoidal wave

Can someone help me come up with a formula that will smoothly transition from a starting value to an end value over a specified time using a Sin or Cos wave? I'm attempting to replicate a bouncing effect like the one shown in my sample using CSS and ...

Strategies for formatting JSON data in a controller

As someone who is new to AngularJS and JSON, I am facing an issue when trying to filter out unnecessary fields in the JSON data. In my controller, I have the following code snippet: var data = $scope.choices; // This is an array var datav = (JSON.stringi ...

Issue with JQuery causing Google map to partially load

Trying to incorporate GoogleMap into a hash page within my project has been a bit challenging. When transitioning from one page to the map page, the GoogleMap only loads partially. Interestingly, upon refreshing the hash page, it loads successfully. The fu ...

Retrieve data from a function using a jQuery plugin

Highlighted Text: <p>Hello, World!</p> Source Code: $('p').click(function(){ $(this).text('Text has been clicked'); }); Custom Plugin: (function($){ $.fn.modifyText = function(action) { return this.e ...

Toggle the visibility of divs by swapping image on click

As a beginner in the realm of coding with Javascript, html, and related technologies, I am seeking guidance on how to enhance my current work. My goal is to create a webpage featuring 4 images serving as buttons, each corresponding to 4 hidden divs with d ...

Errors during the compilation of Webgl shaders in the Google Chrome browser

Currently, I am in the process of learning three.js by following this tutorial: . Despite the tutorial working well, I have encountered errors in my own code which seem like this: ERROR: 0:26: 'nuniform' : syntax error Three.js:325 precision hi ...

c3.js Error: The value of b is not defined

Struggling to create a graph using a JSON object generated in PHP. Despite following the documentation example, I keep encountering a TypeError: b.value is undefined in the JS log. The data seems to be structured correctly. for($i = 0; $i < 10; $i++){ ...

Error 8007 encountered when attempting to scale at 100% proficiency. Transformation unsuccessful

Wondering if this could be a bug in Photoshop. When scaling a layer and entering values of 100%, an error message pops up: var srcDoc = app.activeDocument; var numOfLayers = srcDoc.layers.length; // main loop for (var i = numOfLayers -1; i >= 0 ; i-- ...

What is the best way to locate all complete words within a string, up to 65 characters in length?

Looking to enhance my titles for better Google SEO (using title tag in html). My product titles are currently 3-4 lines long and do not look appealing. I am looking for a way to identify the last complete word before the 65th character in a string. For e ...

translating a C++ buffer into a utf-8 string using node.js

I'm facing an issue with my server-side code written in C++ that returns a string. The client-side code is hosted in express and makes calls to the endpoint like so: router.post( '/returnMyStringFromCPlusPlus', ( request, response ) => ...

Using classic ASP to populate a JavaScript array from a VBScript drop-down menu

To create a JavaScript array based on the selected values from multiple drop down lists, each with the same name due to being generated in a for loop, the following code snippet is currently being used: <script language="JavaScript"> var array ...

Integrating chat functionality with a structured data format

Considering creating a collaborative communication platform, I am contemplating whether to develop a comprehensive application in JavaScript with MVC architecture or utilize it solely for managing message delivery using Node.js and socketIO. Would it be m ...

Out of nowhere, my React App has decided to stop working despite no recent changes

Hi everyone, I recently forked a React app from https://github.com/conedex/frontend. It was working perfectly fine until it suddenly stopped with this error message: ./node_modules/@metamask/utils/node_modules/superstruct/dist/index.mjs 46:43 Module parse ...

The final child element is null when using lastElementChild

For my current Javascript project, I am tackling the task of dividing the page into two separate div elements. The left div is populated with randomly positioned images, and then I utilized the .cloneNode() method to duplicate this on the right side, exclu ...