sourlemonaid - 8 months ago 40

Javascript Question

I have an array of strings and the strings hold numbers inside of them. I also have a set of operations i need to perform on those numbers. They follow the order of +, -,*, /. if the amount of numbers is more than 4 then it goes back to the plus sign.

`function calculate(n, operator, b) {`

switch (operator) {

case 1:

n += b;

return n;

case 2:

n -= b;

return n;

case 3:

n *= b;

return n;

case 4:

n /= b;

return n;

}

}

numberArray = ["23", "44", "99", "324", "19"]

let n=0;

let c = 1;

for (var i = 0; i < numberArray.length; i++) {

calculate(n, c, parseInt(numberArray[i]));

if ( c < 4) {

c++;

} else {

c=1;

}

}

console.log(n);

for some reason the switch statement doesn't run correctly. it doesn't perform the operations and return the

`n`

Answer

i thought the

`n += b`

; in the function would update the value of`n`

.

It does, but that `n`

isn't the `n`

in your code *calling* `calculate`

. It's the `n`

that's an argument to `calculate`

. When you do:

```
calculate(n, c, parseInt(numbersArray[i]));
```

the **value** of `n`

is passed into `calculate`

, not something that refers to the variable itself. (This is called "passing by value." JavaScript always passes the *value* of a variable.) The argument is like a local variable; updating it has no effect outside the function.

Simply use the result:

```
n = calculate(n, c, parseInt(numbersArray[i]));
```

Updated snippet:

```
function calculate(n, operator, b) {
switch (operator) {
case 1:
n += b;
return n;
case 2:
n -= b;
return n;
case 3:
n *= b;
return n;
case 4:
n /= b;
return n;
}
}
numberArray = ["23", "44", "99", "324", "19"]
let n=0;
let c = 1;
for (var i = 0; i < numberArray.length; i++) {
n = calculate(n, c, parseInt(numberArray[i]));
if ( c < 4) {
c++;
} else {
c=1;
}
}
console.log(n);
```

Of course, this means your `switch`

can be simpler:

```
switch (operator) {
case 1:
return n + b;
case 2:
return n - b;
case 3:
return n *= b;
case 4:
return n / b;
}
```

Just FWIW, there's a clever way to update `c`

as well, to avoid the `if`

:

```
c = (c % 4) + 1;
```

That'll wrap around for you.

Source (Stackoverflow)