Subtracting prompt reponse from Variable | Sololearn: Learn to code for FREE!
+ 1

Subtracting prompt reponse from Variable

How do I subtract from what my user inputs if Im using a local var function inputYourNeeds(){ var food = parseInt(prompt("How much do you spend on food?)); needs = needs - food; } needs is a global var that has 0; as the value the user is prompted what their income is, and the needs var now equals budget * .5;

18th Apr 2018, 7:09 PM
A B
A B - avatar
9 Réponses
+ 2
Good rule of thumb is if something doesn't HAVE to be global, don't make it global. In the case of your function and local vars, just use the 'return' statement to return the values back. That'll keep your variables protected but allow you to do things as you expect.
18th Apr 2018, 7:21 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 2
Gotcha. Just add a 'return' statement to the end of your function and have it return the calculated value back, in this case the variable 'needs' Loose example: let needs = 10; function inputYourNeeds(){ let food = parseInt(prompt("How much do you spend on food?")); needs -= food; return needs; } document.write(inputYourNeeds());
18th Apr 2018, 7:19 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 1
well when I run it it only shows me a dollar sign when it should show me what the remaining amout is left in my needs and how much over my budget or under I am
18th Apr 2018, 7:17 PM
A B
A B - avatar
+ 1
Without me seeing your exact code, it's hard for me to speculate since I can't see what you're already doing or not. If you want to post up all of your code, I'd be more than happy to assist.
18th Apr 2018, 7:20 PM
Fata1 Err0r
Fata1 Err0r - avatar
0
how can I code that without food, rent, etc.. showing?
18th Apr 2018, 7:18 PM
A B
A B - avatar
0
should i make all my prompts global?
18th Apr 2018, 7:19 PM
A B
A B - avatar
0
var person = ""; var budget = 0; needs = 0; savings =0; wants =0; function myBudget(){ person = prompt("what is your monthly income?"); budget = parseInt(prompt("what us your monthly income?")); needs = budget * .5; savings = budget *.2; wants = budget * .3; }
18th Apr 2018, 7:25 PM
A B
A B - avatar
0
then there is the inputYourNeeds function
18th Apr 2018, 7:26 PM
A B
A B - avatar
0
I can not add a return because I have several other variables to input and I have to add a .append to the last var
18th Apr 2018, 7:49 PM
A B
A B - avatar