JavaScript basic calculator app failed to generate an error as anticipated

For my homework assignment, I am developing a basic calculator application using JavaScript. My main task is to ensure that the input numbers are limited to only two and that they are valid numbers; otherwise, an error should be thrown.

Initially, concerning the addition operation exclusively, my initial code was as follows:

function add(number1, number2) {
  if (arguments.length !== 2) {
    throw new Error('Please provide two numbers');
  }
  if (!Number.isFinite(number1) || !Number.isFinite(number2)) {
    throw new Error('Only numerical values are allowed');
  }
  return number1 + number2;
}

The code seemed functional upon testing with console.log. However, to prevent redundancy in validations, I decided to create a separate function encapsulating these checks for reusability. Subsequently, I encountered issues with error throwing and found it perplexing.

function inputValidation(number1, number2) {
  if (arguments.length !== 2) {
    throw new Error('Please provide two numbers');
  }
  if (!Number.isFinite(number1) || !Number.isFinite(number2)) {
    throw new Error('Only numerical values are allowed');
  }
}

function add(number1, number2) {
  inputValidation(number1, number2);
  return number1 + number2;
}

While the usage of Number.isFinite continued to operate effectively, the arguments’ length validation appeared to malfunction without clear reasoning. The test conducted produced the subsequent error message:

1) error occurs when not precisely two arguments are given
       should throw Please provide two numbers:
     AssertionError [ERR_ASSERTION]: Missing expected exception (Error).

I'm puzzled by this issue. Any insights would be greatly appreciated. Thank you.

Answer â„–1

When your add function passes 2 arguments to inputValidation, if number1 or number2 is missing, it defaults to using undefined as the argument.

Instead of checking arguments.length !== 2, a more effective approach would be to verify that at least one of the arguments is not undefined with

if (!(number1 && number2))

To see an example, visit this JSFiddle link

You may also choose to only validate whether both arguments are numbers. In such case, consider changing the error message to 'please enter 2 numbers'.

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

Exploring JSON data and making precise adjustments in JavaScript

I am attempting to create my own database using JavaScript and JSON, but I have encountered some issues along the way. My main struggle is figuring out how to extract specific content from a JSON file. After doing some research, I came across this code sn ...

Creating a customized image modal in ReactJS that incorporates a dynamic slideshow feature using the

I am attempting to incorporate an image lightbox into my React application: https://www.w3schools.com/howto/howto_js_lightbox.asp Here is the link to the CodeSandbox where I have tried implementing it: https://codesandbox.io/s/reactjs-practice-vbxwt ...

Node.js program experiences issues with incorporating netCDF files

I am attempting to encode a NetCDF file within my Node.js program using the netcdf library, which can be found at https://www.npmjs.com/package/netcdf. After running the program, I encountered the following error: C:\app [master +2 ~1 -0 !]> npm ...

Incorporating JSTree Into Your Website's Heading: A Step-By-Step

I'm in search of a way to integrate the following code snippet as a JSTree into the heading section of a webpage, depicted below: <div id="jstree"> <ul> <li>Core 1 <ul> & ...

Text aligned at the center of the Y and X axis

I am looking to center my content along the Y axis instead of only on the X axis. To prevent the page from expanding beyond its current size, I have applied the following CSS: html { overflow-y: hidden; overflow-x: hidden } What I want to achieve is havi ...

Adding an additional parameter in the ListItem onMouseOver function

Within my React code base, I have a material-ui ListItem that looks like this: <ListItem button key={currIndex} onMouseOver={handleOnMouseClickOnListItem}> The handler function in my code (using Flow typing) is as follows: const handleOnMouseClic ...

Is it possible to use window.print() to print the entire contents of a DIV with both horizontal and vertical scroll bars?

In my code, I have a div that contains both horizontal and vertical scrollers. Whenever I try to print the content inside this div using the window.print() method, it only prints the visible portion of the div. Here is the code snippet that I have attempte ...

Display a popup notification when clicking in Angular 2

Can anyone help me with displaying a popup message when I click on the select button that says "you have selected this event"? I am using Angular 2. <button type="button" class="button event-buttons" [disabled]="!owned" style=""(click)="eventSet()"&g ...

What is the method for showcasing background images sequentially?

css code #intro { position: relative; background-attachment: fixed; background-repeat: no-repeat; background-position: center top; -webkit-background-size: cover; -moz-background-size: cover; backgr ...

Tips for adding a string variable to a JQuery HTML element attribute

Hi there, I've been working on a JQuery code to append data to a div element and it's been successful so far. Here is the code: $('#conversation').append('<div id="receiver"><p><b>' + username + ':< ...

Managing global HTTP response errors on Vue/axios using Vuex

I've encountered an issue in my VueJS SPA where a strange limbo state occurs. The application fails to recognize that the JWT token has expired, leading it to still display as if the user is logged in. This typically happens after periods of hibernati ...

Is there a way to remove specific elements from an array without using jQuery?

I've recently started diving into Javascript, experimenting with Tampermonkey scripts for the past week. The webpage I'm currently working on features dynamic elements that appear randomly with each page load. Sometimes only one element like "he ...

Is there a way to prevent Express from automatically adding a slash to a route?

Despite my extensive search for a solution, none of them have proven effective. Perhaps you could provide some assistance. I'm currently working on a Node.JS and Express-based plugin webserver. The main code for the webserver is as follows: This sec ...

Initiate a Gravity Forms form refresh after modifying a hidden field with jQuery

TO SUM IT UP: Is there a way in Javascript to activate an update on a Gravity Form that triggers the execution of conditional logic? ORIGINAL QUESTION: I'm using Gravity Forms and I have set up an "on change" event $('#gform_1').find(&apos ...

Ways to deactivate a button with a designated identification through iteration using jQuery

Can't Figure out How to Deactivate a Button with Specific ID $('.likes-button').click(function(){ var el= this; var button1 = $(el).attr('id'); console.log(button1) $('#button1').attr("disabled",true); }) ...

HTML Buttons Remain Selected After Being Clicked

Currently working on a calculator app for a class project but I've hit a roadblock while setting up keyboard listeners. The keyboard functionality is fine, however, when it comes to clicking on buttons, specifically the non-keyboard functions, they re ...

The unexpected disappearance of data in a d3 v4 map leaves users puzzled

My current task involves reading data from a csv file and creating a map where the key is the state abbreviation and the value is the frequency of that state in the data. The code I have successfully creates the map, reads in the data, and when I use cons ...

Is there a way to redirect using Express JS when the destination is

Hello there, I'm encountering an issue with redirecting in express js. I have a function that should trigger when a submit button is pressed and then redirect to a different page. However, when using res.redirect('/results.ejs');, I receive ...

How do I utilize the file handler to execute the flush method within the Deno log module using Typescript?

I'm having trouble accessing the fileHandler object from my logger in order to flush the buffer to the file. This is the program I am working with: import * as log from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_emai ...

Is it possible to generate a component dynamically using a string template?

I have a Component called "CDataTable" that renders columns in a for loop. Inside the loop, there is a template: <template v-if="typeof col.template !== 'undefined'" #body="{data}"> <component :is="compile(co ...