
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
How to force JavaScript to do math instead of putting two strings together?
Let’s say, we have an array of strings, basically it is an array of number strings like this −
const arr = ['3', '3', '55', '23', '67', '43', '12', '67', '87', '12'];
We are required to write a JavaScript function that takes in one such array and returns the sum of all elements of this array instead of concatenating the string to one another.
Let’s write the code for this function −
Example
const arr = ['3', '3', '55', '23', '67', '43', '12', '67', '87', '12']; const sumString = arr => { const num = arr.reduce((acc, val) => { const sum = acc + (+val || 0); return sum; }, 0); return num; }; console.log(sumString(arr));
The unary (+) operator, before any string forces explicit type coercion from type String to type Number, if the first character of the string is not a valid number, then NaN is returned otherwise a valid number is returned.
Output
The output in the console will be −
372
- Related Articles
- Can we do math operation on Python Strings?
- Adding binary strings together JavaScript
- How to do Python math at command line?
- How To Do Math With Lists in python ?
- How to force MongoDB to use the BasicCursor instead of an index?\n
- How to force MySQL to connect by TCP instead of a Unix socket?
- How to merge two strings alternatively in JavaScript
- How to do case insensitive string comparison of strings in JavaScript
- JavaScript: How to Find Min/Max Values Without Math Functions?
- How to compare two strings in the current locale with JavaScript?
- How do you feel about putting pineapple on pizza?
- How to plot two histograms together in R?
- JavaScript Math Object example
- Twice join of two strings in JavaScript
- Finding gcd of two strings in JavaScript

Advertisements