Categories
JavaScript Answers

How to force JavaScript to do math instead of putting two strings together?

Spread the love

Sometimes, we want to force JavaScript to do math instead of putting two strings together.

In this article, we’ll look at how to force JavaScript to do math instead of putting two strings together.

How to force JavaScript to do math instead of putting two strings together?

To force JavaScript to do math instead of putting two strings together, we should make sure we’re using arithmetic operators with numbers.

For instance, we write

const x = +"11.5" + +"3.5";

to convert '11.5' and '3.5' to numbers with the unary + operator.

Then we add the returned numbers together and assign the sum to x.

Conclusion

To force JavaScript to do math instead of putting two strings together, we should make sure we’re using arithmetic operators with numbers.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *