I am attempting to obtain the sum using the return function, but I am having trouble getting it to work. Would you be able to assist me in identifying what mistake I am

Can someone explain the benefits of using a return function?

var a, b;

function addNumbers(a, b) {
  a = prompt("Enter a number");
  b = prompt("Enter another number");
  return (a + b);
}
addNumbers();

Answer №1

.prompt() will give you a string, but if you need a number, use methods like parseInt() or parseFloat():

var num1, num2, sum;

function addition(num1, num2) {
  num1 = parseInt(prompt("Type a number"));
  num2 = parseInt(prompt("Type another number"));
  return (num1 + num2);

}
console.log(addition());

Answer №2

To store the values of x and y in your predefined variables, simply remove them as arguments from the test function - this way it will utilize the already stored values:

var x, y, result;

function test() {
  x = parseInt(prompt("Enter a number"), 10);
  y = parseInt(prompt("enter another Number"), 10);

  return x + y;
}

console.log(test(), x, y);

Additionally, following @j08691's advice, make sure to convert the results of prompt to numbers before performing any calculations.

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

The compiler detected an unanticipated keyword or identifier at line 1434. The function implementation is either absent or not placed directly after the declaration at line 239

Having trouble implementing keyboard functionality into my snake game project using typescript. The code is throwing errors on lines 42 and 43, specifically: When hovering over the "window" keyword, the error reads: Parsing error: ';' expecte ...

What causes the initial AJAX response to be delayed by 10 seconds when using setInterval()?

I have a task that requires me to send an ajax request to display an image that changes every 10 seconds. However, I'm encountering an issue where my webpage remains blank for the first 10 seconds and only displays the first image after the initial de ...

Unable to properly connect my CSS file to the header partial

I am struggling to include my CSS file in the header partial Here is the link I am using: <link rel="stylesheet" href="stylesheets/app.css"> This is what my directory structure looks like: project models node_modules public stylesh ...

Struggling to access the "this.array" variable within a TypeScript-powered Angular 4 application

I cannot access the this.array variable in my TypeScript-Angular 4 application. The error is being thrown at this.services.push because this.services is undefined. My code looks like this: export class ServersComponent implements OnInit { //Initializi ...

I am wondering why the content is not showing up when using state.map(foo => <>{foo}</>) in my code

Why does the first tsx code display the state.map properly while the second code displays nothing? Despite both pieces of code performing the same task in the same way, one list is correctly displayed while the other state.map has never rendered anything, ...

Can an onload function be triggered within the location.href command?

Can a function be called onload in the location.href using jQuery? location.href = getContextPath() + "/home/returnSeachResult?search=" + $('#id-search-text-box').val() + "&category=" + $('#search_concept').text() + "onload='j ...

Tips for storing a GET response in a variable using ExpressJS and LocomotiveJS

I am currently navigating the world of NodeJS and have successfully developed an app using ExpressJS and LocomotiveJS framework. I am now faced with a challenge: how do I store a particular GET response in a variable within a controller? For instance: fil ...

Dealing with two form submissions using a single handleSubmit function in react-hook-form

I have a React app with two address forms on one page. Each form has its own save address function that stores the address in the database. There is a single submit button that submits both fields and redirects to the next page (The plus button in the circ ...

Tips for ensuring a controller function only runs once in AngularJS

I have a controller that is being referenced in some HTML. The HTML changes on certain events, causing the controller function code to execute multiple times. The issue lies in a portion of the code that should only be executed once. Shown below is the ...

How to eliminate subdomains from a string using TypeScript

I am working with a string in TypeScript that follows the format subdomain.domain.com. My goal is to extract just the domain part of the string. For example, subdomain.domain.com should become domain.com. It's important to note that the 'subdoma ...

Javascript/Webpack/React: encountering issues with refs in a particular library

I've encountered a peculiar issue that I've narrowed down to the simplest possible scenario. To provide concrete evidence, I have put together a reproducible repository which you can access here: https://github.com/bmeg/webpack-react-test Here&a ...

Webpack Error: SyntaxError - an unexpected token found =>

After transferring my project to a new machine, I encountered an error when running webpack --watch: C:\Users\joe_coolish\AppData\Roaming\npm\node_modules\webpack\bin\webpack.js:186 outputOption ...

Combining a random selection with a timer in JavaScript for a dynamic user experience

Currently, I am developing a Twitter bot using JavaScript, Node.js, and the Twit package. The goal is for the bot to tweet every 60 seconds with a randomly selected sentence from an array. When testing the timer and random selection function individually, ...

Modify the database once authorized by the administrator

`I have a webpage that showcases testimonials. I am looking to only display the testimonials with a "status" of "1" in my database. How can I quickly update the "status" column from "0" to "1" right after the admin clicks on update? I am also incorporati ...

javascript search for parent function argument

I am struggling to figure out how to locate the key in my json array. When I try to find the key using a function parameter, it does not seem to work. This is a snippet of my json data: ... { "product": [ { "title": " ...

Is it possible to replicate jQuery's method of creating custom events in vanilla JavaScript?

Hey there! I'm interested in creating events in JavaScript similar to how jQuery does it. Does anyone have insight on how jQuery accomplishes this? I've noticed that using vanilla JavaScript like this: var myEvent = new CustomEvent("userLogin", ...

Transferring checkbox status from HTML (JavaScript) to PHP

I am a beginner in JavaScript and I am trying to get the value from a variable in JS, send it via post (or ajax) to a PHP file, and display the text. However, I have attempted various methods but always encounter an undefined index error in PHP. Below is ...

Improving user experience through real-time form validation in CodeIgniter with the

As I am working on a form with fields such as Fullname, Password, and Mobile no, each field is initially displayed individually on the page. When a user clicks on a button, the next field should be displayed while setting AJAX validation on it. The goal is ...

Exploring the power of Vue 3 and Vuex with Typescript to access class methods

Can Vuex state be used to access class methods? For example, in this scenario, I am attempting to invoke fullName() to show the user's formatted name. TypeError: store.state.user.fullName is not a function Classes export class User { constructo ...

What is the method for incorporating a timeout in a promise?

After exploring various methods for adding timeouts to promises, it appears that most rely on the setTimeout() function. Here is the formal definition: The setTimeout() function executes a specified function or evaluates an expression after a set number of ...