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
Selected Reading
How to add a number and a string in JavaScript?
In JavaScript, when you use the + operator with a number and a string, JavaScript performs concatenation instead of mathematical addition. This is because the presence of a string changes the operation from addition to string concatenation.
How It Works
JavaScript follows these rules when using the + operator:
- Number + Number: Mathematical addition
- String + Number: String concatenation (number is converted to string)
- Number + String: String concatenation (number is converted to string)
Example
<html>
<body>
<script type="text/javascript">
var a = 5 + 5; // Number + Number = Addition
var b = "5" + 5; // String + Number = Concatenation
var c = 5 + 5 + "5" + 5; // Mixed: (5+5) first, then concatenation
var d = "Hello" + 5; // String + Number = Concatenation
document.write(a + "<br>" + b + "<br>" + c + "<br>" + d);
document.write("<br><br>Types:<br>");
document.write(typeof(a) + "<br>");
document.write(typeof(b) + "<br>");
document.write(typeof(c) + "<br>");
document.write(typeof(d));
</script>
</body>
</html>
Output
10 55 1055 Hello5 Types: number string string string
Understanding Variable 'c'
In the expression 5 + 5 + "5" + 5, JavaScript evaluates left to right:
-
5 + 5=10(number addition) -
10 + "5"="105"(concatenation - number converts to string) -
"105" + 5="1055"(concatenation continues)
Converting Back to Number
If you need mathematical addition with strings that contain numbers, use conversion methods:
<html>
<body>
<script type="text/javascript">
var result1 = Number("5") + 5; // Convert string to number
var result2 = parseInt("5") + 5; // Parse string to integer
var result3 = parseFloat("5.2") + 5; // Parse string to float
document.write("Number(): " + result1 + "<br>");
document.write("parseInt(): " + result2 + "<br>");
document.write("parseFloat(): " + result3);
</script>
</body>
</html>
Output
Number(): 10 parseInt(): 10 parseFloat(): 10.2
Conclusion
When adding numbers and strings in JavaScript, the + operator performs concatenation, not mathematical addition. Use conversion methods like Number() or parseInt() when you need actual numeric addition with string values.
Advertisements
