Make sure the values are numbers, otherwise they will concat instead of suming.
Copya = parseInt(a, 10); // a is now int
Answer from kjetilh on Stack OverflowMake sure the values are numbers, otherwise they will concat instead of suming.
Copya = parseInt(a, 10); // a is now int
Your code is adding (concatenating) strings. Are you sure that the code you posted represents your problem? What you have written should work. Be sure in the real code you're not saying:
Copyvar a = '2'; // or something similar
Or if the values are parsed from somewhere, be sure to call parseInt(a, 10) on them before doing the addition, 10 being the radix.
Or as pointed out in the comments the Number function would probably suit your purposes.
Videos
This'd be exactly the job for reduce.
If you're using ECMAScript 2015 (aka ECMAScript 6):
Copyconst sum = [1, 2, 3].reduce((partialSum, a) => partialSum + a, 0);
console.log(sum); // 6
Run code snippetEdit code snippet Hide Results Copy to answer Expand
For older JS:
Copyconst sum = [1, 2, 3].reduce(add, 0); // with initial value to avoid when the array is empty
function add(accumulator, a) {
return accumulator + a;
}
console.log(sum); // 6
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Isn't that pretty? :-)
Recommended (reduce with default value)
Array.prototype.reduce can be used to iterate through the array, adding the current element value to the sum of the previous element values.
Copyconsole.log(
[1, 2, 3, 4].reduce((a, b) => a + b, 0)
)
console.log(
[].reduce((a, b) => a + b, 0)
)
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Without default value
You get a TypeError
Copyconsole.log(
[].reduce((a, b) => a + b)
)
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Prior to ES6's arrow functions
Copyconsole.log(
[1,2,3].reduce(function(acc, val) { return acc + val; }, 0)
)
console.log(
[].reduce(function(acc, val) { return acc + val; }, 0)
)
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Non-number inputs
If non-numbers are possible inputs, you may want to handle that?
Copyconsole.log(
["hi", 1, 2, "frog"].reduce((a, b) => a + b)
)
let numOr0 = n => isNaN(n) ? 0 : n
console.log(
["hi", 1, 2, "frog"].reduce((a, b) =>
numOr0(a) + numOr0(b))
)
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Speed Optimized
The reduce way is nice as it is easy to write and generally simple to understand, but if you are looking for speed (which is usually not a concern), use a simple for loop.
Copyconst numbers = [1, 2, 3, 4];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Non-recommended dangerous eval use
We can use eval to execute a string representation of JavaScript code. Using the Array.prototype.join function to convert the array to a string, we change [1,2,3] into "1+2+3", which evaluates to 6.
Copyconsole.log(
eval([1,2,3].join('+'))
)
//This way is dangerous if the array is built
// from user input as it may be exploited eg:
eval([1,"2;alert('Malicious code!')"].join('+'))
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Of course displaying an alert isn't the worst thing that could happen. The only reason I have included this is as an answer Ortund's question as I do not think it was clarified.