I can't figure out why my code is only returning the else statement and an undefined value instead of the totalBasketballScore

I was confident that my code was correct, but I am encountering an issue when trying to calculate basketball scores based on free throws, 2 pointers, and 3 pointers. Whenever I console.log the totalBasketballScore, the output is 'All entries must be numbers' and undefined. What adjustments do I need to make to ensure that I get the correct score when inputting the three values as parameters?

function totalBasketballScore(numberFreeThrows, numberMidRange, numberThreePointers) {
  const freeThrows = 1;
  const midRange = 2;
  const threePointers = 3;

  if (typeof numberFreeThrows === 'number' && numberMidRange === 'number' && numberThreePointers === 'number') {
    let totalFreeThrows = freeThrows * numberFreeThrows;
    let totalMidRange = midRange * numberMidRange;
    let totalThreePointers = threePointers * numberThreePointers;
    let gameTotal = totalFreeThrows + totalMidRange + totalThreePointers;
    return gameTotal;

  } else {
    console.log('All Entries Must Be a Number');
  }
}
console.log(totalBasketballScore(1, 2, 4));

Answer №1

One way to tackle this issue is by utilizing the isNaN() method. This function can be employed to verify if a value is considered Not a Number. If isNaN() evaluates to false, then the value is indeed a number.

function calculateFinalScore(threePointAttempts, twoPointAttempts, freeThrowAttempts) {
const threePoints = 3;
  const twoPoints = 2;
  const freeThrows = 1;

  if(!isNaN(threePointAttempts) && !isNaN(twoPointAttempts) && !isNaN(freeThrowAttempts)) {
    let totalThreePointScore = threePoints * threePointAttempts;
    let totalTwoPointScore = twoPoints * twoPointAttempts;
    let totalFreeThrowScore = freeThrows * freeThrowAttempts;
    let finalScore = totalThreePointScore + totalTwoPointScore + totalFreeThrowScore;
    return finalScore;

  } else {
    console.log('Please enter valid numeric values for all attempt types.');
  }
}
console.log(calculateFinalScore(4, 5, 2));

Answer №2

To ensure proper data type validation for each parameter, it is recommended to use the typeof operator in the following manner:

if(typeof numberFreeThrows === 'number' && typeof numberMidRange === 'number' && typeof numberThreePointers === 'number'){

} else {

}

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

Determine if every object in the array contains a specific key value pair

I am dealing with the following JSON data: { records:{ data:{ current:{ records:{ '2years':[{a:1, b:2, flag:true}, {a:2, b:4}, ...

Error: Functionality cannot be achieved

Looking for assistance in resolving this issue. Currently, I am attempting to register a new user and need to verify if the username already exists or not. Below is the factory code used for this purpose: .factory('accountService', function($res ...

"Reposition all elements contained within a div that have a specific class

I'm completely new to Javascript and I've been trying to move all elements with a specific class inside a particular div. After doing some research, I found a solution that worked using IDs. However, when I tried to adapt it to work with classNam ...

When submitting a form with a contenteditable div and text box using JQuery, the POST request is not

I developed a website that allows users to edit and format text, then save it onto the server. Utilizing jquery to send the data to a PHP page for saving, I encountered an issue where the site fails to send the file name along with the formatted text to PH ...

Avoiding a constantly repeating video to prevent the browser from running out of memory

Using HTML5, I created a video that loops and draws the frames to canvas. I decided to create multiple canvases and draw different parts of the video on each one. However, after some time, I encountered an issue where Google Chrome would run out of memory. ...

JavaScript: converting to string

Why does Object.prototype.toString === toString? When I include the following code in the global scope: var toStringValue = toString.call("foobaz"); I assume that toStringValue would be the value of window.toString since window is the default scope, corre ...

"Exploring the New Features of Bootstrap 5: Button Collapse and

I am struggling to get two buttons working with Bootstrap 5. The first button is supposed to trigger two JavaScript functions to open a bootstrap carousel. The second button is a simple collapse button designed to reveal a long text string. Unfortunately, ...

Creating automatic page additions using Node.js on Heroku?

Can you assist me with a challenge I'm facing? Currently, I am using node.js and heroku to deploy an application and each time I add a new post, I have to manually update my web.js file. This process was manageable when I had fewer pages, but now it&a ...

Show or hide a Div based on radio button selection problem

I've successfully implemented a Div visibility toggle using the code below: $('input[name="type"]').on('change', function() { var show = $(this).val(); $(".typechoice").hide(); $("#"+show).show(); }) <script src="h ...

Step-by-step guide to displaying the dropdown menu button content at the top of the page in main.html by using the frameset tag

The layout of my main.html involves displaying menu.htm and welcome.htm using frameset. One issue that arises is with the drop-down menu buttons "Admin..." and "Scheduler...". When hovering over these buttons, the dropdown content does not display properly ...

What is the process behind Stackoverflow's "Congratulations, you've earned a new badge" popup window?

Possible Duplicates: Custom notify box similar to StackOverflow Creating popup message like StackOverflow How does StackOverflow implement the "You earned a new badge" window? (the orange one that pops up at the top of the screen, I believe it&ap ...

Exploring the Differences between Angular's Http Module and the Fetch API

While I grasp the process Angular uses for HTTP requests, I find myself leaning towards utilizing the Fetch API instead. It eliminates the need to subscribe and unsubscribe just for a single request, making it more straightforward. When I integrated it int ...

Applying CSS classes to a custom AngularJS directive: A step-by-step guide

Need to have a CSS class called tab for the nav HTML element, which will be used as a directive: <nav tab></nav> The expected interpretation is: <nav class="tab"> <a></a> <a></a> <a></a> ...

Is it possible to align the radio-button label above the radio-button in Angular Material 2?

Currently, I am utilizing angular material 2 (material.io) and attempting to position the label of the md-radio-button above the radio button itself. Here's an illustration: View Radio Buttons The official documentation mentions that you can easily ...

Learn how to showcase vertical text in React Native similar to a drawer

Looking for a way to display text vertically in a dynamic manner, where the length of the text can vary. Below are some examples for reference: Example 1 Example 2 <View> <View style={{}}> <View style={{ marginTop: 30, flexDire ...

Struggling to pass a function argument as a string for use within the function

Although the title may seem unclear, I will clarify. I have a collection of images on the left side and I have implemented an onclick function on each one to display the image and some information on the right side. It's like having thumbnails on the ...

Using JavaScript values retrieved from a database to dynamically adjust the options in the second dropdown menu based on the selection made in the

I am currently working on a feature that involves populating two dropdown menus with values from a database. The idea is that when an option is selected in the first dropdown, the second dropdown should dynamically display relevant values based on that s ...

Tips for utilizing canReuse and routerOnReuse in Angular 2

I've reviewed the information provided in this link, but I'm still unsure about how to effectively utilize it. My requirement is straightforward—I need to update a parameter in the URL without constantly sending API requests, which are current ...

The collapsible tree nodes overlap one another in the D3.js visualization

I'm currently working on integrating a d3 code into Power BI for creating a collapsible tree structure. Each node in the tree is represented by a rectangular box, but I've run into an issue where nodes overlap when their size is large. Below is t ...

Steps for adding a variable to a JSON request

I'm new to JavaScript and React Native and I'm looking for a way to include variables in a JSON request. Specifically, when making a JSON request using Fetch or Axios to a URL, I need to customize the URL based on certain parameters. For instance ...