How to add a number and a string in JavaScript?
In JavaScript, the plus + operator is used for numeric addition and string concatenation. To adds the number to a string Just use plus between the number and string in Javascript.
String + Number = Concatenated string
Number + Number = The sum of both numbers
String – Number = The difference between (coerced string) and the number
Note: When you “add” a number to a string the interpreter converts your number to a string and concatenates both together.
Example of JavaScript add the number to a string
If we try to add a number and a string then, as addition is not possible, ‘concatenation’ takes place.
In the example adding a number (integer) and string, also checking the output type.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<body>
<script>
var num1 = 10 + ' str ';
console.log(num1);
console.log(typeof num1);
</script>
</body>
</body>
</html>
Output:
Some Examples:-
"" + 1 === "1"
"1" + 10 === "110"
"110" + 2 === "1102"
"1102" - 5 === 1097
1097 + "8" === "10978"
Do comment if you have any questions and suggestion on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version