Reputation: 158
I am writing a calculator program with a user interface similar to a real calculator. Everything had been going fine (unusual for me xD) until I needed to have multiple values returned from one function (I read on another post that this can be done with an array). I haven't been returning the values to any specific place so I think they are just being sent out to the global scope, and this has worked so far with other functions like updateDisplay()
. However, when I try to return returnValue
from operationClick()
, it doesn't send the changes outside of the function.
Here are some bits and pieces of my code (hopefully enough so you can find what I'm doing wrong):
returnValue = [false, undefined];
numberArray = new Array;
function operationClick(operation, concat, returnValue) {
if (operation == "equals") {
concatComplete = returnValue[1] + concat;
$('.screen_text').html(Number(concatComplete));
}
else if (operation == "add") {
returnValue = [true, concat + "+"];
console.log(returnValue); // The new value is correct here but not anywhere else :(
}
return returnValue; // Something goes wrong here!
}
function updateDisplay(array) {
concat = array.join("");
$('.screen_text').html(concat);
return concat
}
function numberClick(number, returnValue) {
if (returnValue[0] == true) {
// This should run once operationClick() else if statement runs but it doesn't
numberArray = new Array;
$('.screen_text').html("");
}
numberArray.push(number);
updateDisplay(numberArray);
return numberArray;
}
$('.button_1').click(function(){
numberClick(1, returnValue);
});
$('.button_addition').click(function(){
operationClick("add", concat);
})
$('.button_equals').click(function(){
operationClick("equals", concat, returnValue);
})
Thank you in advance for your help. It is greatly appreciated! I hope my code isn't too messy.
Upvotes: 0
Views: 1080
Reputation: 781350
As mentioned in the comments, returning a value doesn't automatically update anything, you need to do something with the returned value in the caller. If you want to replace the returnValue
global variable with the new value, do it with an assignment.
$('.button_addition').click(function(){
returnValue = operationClick("add", concat);
});
This doesn't happen in the operationClick()
function itself because it has declared a local variable named returnValue
(function parameters are automatically made local variables), and this shadows the global variable. You could also solve the problem simply by giving the function parameter a different name.
function operationClick(operation, concat, oldReturnValue) {
if (operation == "equals") {
concatComplete = oldReturnValue[1] + concat;
$('.screen_text').html(Number(concatComplete));
}
else if (operation == "add") {
returnValue = [true, concat + "+"];
console.log(returnValue); // The new value is correct here but not anywhere else :(
}
}
Upvotes: 1