I am trying to create a function that I can reuse with any string, passing a string as a first parameter and concatenating operator to it as I am trying to create a basic calculator and I am working with couple of strings which display different values for operators(e.g. 'x' instead of '*').
let evalString = '';
let displayString = '';
let currentNumber = '5';
function concOperator(str, operator) {
str += currentNumber + ' ' + operator + ' ';
}
concOperator(evalString, '*');
concOperator(displayString, 'x');
console.log(evalString);
console.log(evalString);
So I expect the evalString to be "5 * " and displayString to be "5 x " after calling a function, but instead it returns empty strings. How could it be fixed?
It's because you're not returning anything in your function and you're not assigning it to your variable. Actually, str
is in the scope of concOperator
function.
A way to fix this:
let evalString = '';
let displayString = '';
let currentNumber = '5';
function concOperator(str, operator) {
return `${str} ${currentNumber} ${operator} `;
}
evalString = concOperator(evalString, '*');
displayString = concOperator(displayString, 'x');