Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to force JavaScript to do math instead of putting two strings together?
JavaScript often concatenates when you expect addition because the + operator works differently with strings and numbers. Here are several methods to force mathematical addition instead of string concatenation.
The Problem
When JavaScript encounters the + operator with strings, it performs concatenation instead of addition:
console.log("3" + "5"); // "35" (concatenation)
console.log(3 + 5); // 8 (addition)
console.log("3" + 5); // "35" (string wins, concatenation)
35 8 35
Using the Unary Plus Operator (+)
The unary + operator converts strings to numbers before addition:
const arr = ['3', '3', '55', '23', '67', '43', '12', '67', '87', '12'];
const sumWithUnaryPlus = arr => {
return arr.reduce((acc, val) => {
return acc + (+val || 0);
}, 0);
};
console.log(sumWithUnaryPlus(arr));
372
Using Number() Constructor
Convert strings explicitly to numbers using Number():
const arr = ['3', '3', '55', '23', '67'];
const sumWithNumber = arr => {
return arr.reduce((acc, val) => {
return acc + Number(val);
}, 0);
};
console.log(sumWithNumber(arr));
151
Using parseInt() or parseFloat()
Use parseInt() for integers or parseFloat() for decimal numbers:
const stringNumbers = ['10', '20.5', '30'];
const sumWithParseInt = stringNumbers.map(str => parseInt(str)).reduce((a, b) => a + b, 0);
const sumWithParseFloat = stringNumbers.map(str => parseFloat(str)).reduce((a, b) => a + b, 0);
console.log("parseInt sum:", sumWithParseInt); // Truncates decimals
console.log("parseFloat sum:", sumWithParseFloat); // Keeps decimals
parseInt sum: 60 parseFloat sum: 60.5
Simple Addition with Type Coercion
Subtract zero to force numeric conversion:
const a = "15"; const b = "25"; console.log(a + b); // "1525" (concatenation) console.log((a - 0) + (b - 0)); // 40 (addition) console.log(a * 1 + b * 1); // 40 (multiplication by 1 converts to number)
1525 40 40
Comparison of Methods
| Method | Handles Decimals | Invalid Input Result | Performance |
|---|---|---|---|
Unary +
|
Yes | NaN | Fast |
Number() |
Yes | NaN | Fast |
parseInt() |
No (truncates) | NaN | Medium |
parseFloat() |
Yes | NaN | Medium |
Conclusion
Use the unary + operator or Number() constructor for reliable string-to-number conversion. Both handle decimals and provide consistent results when forcing mathematical operations in JavaScript.
