Add
The add operator is +.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var result = 1 + 2;
document.writeln(result); //3
</script>
</head>
<body>
</body>
</html>
Rules for add operator:
Operand 1 | Operand 2 | Result |
---|---|---|
NaN | any value | NaN |
any value | NaN | NaN |
Infinity | Infinity | Infinity |
-Infinity | -Infinity | -Infinity |
Infinity | -Infinity | NaN |
+0 | +0 | +0 |
-0 | +0 | +0 |
-0 | -0 | -0 |
string | string | , string concatenation |
string | any value | other operand is converted to a string and the do the string concatenation |
If either operand is an object, number, or Boolean, its toString() method is called to get a string value. undefined becomes "undefined" and null becomes "null" for add operator.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var result1 = 5 + 5; //two numbers
document.writeln(result1); //10
var result2 = 5 + "5"; //a number and a string
document.writeln(result2); //"55"
</script>
</head>
<body>
</body>
</html>
Most common mistakes
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var num1 = 5;
var num2 = 10;
var message = "Result: " + num1 + num2;
document.writeln(message); //"Result: 510"
</script>
</head>
<body>
</body>
</html>
To perform the arithmetic calculation and then append that to the string:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var num1 = 5;
var num2 = 10;
var message = "Result: " + (num1 + num2);
document.writeln(message); //"Result: 15"
</script>
</head>
<body>
</body>
</html>
Home
JavaScript Book
Language Basics
JavaScript Book
Language Basics
Operators:
- JavaScript Operators
- Increment/Decrement Operators
- Increment/Decrement Operators for String, Boolean, Floating-point and Object
- Unary Plus and Minus
- Bitwise Not operator
- Bitwise AND
- Bitwise OR
- Bitwise XOR
- Left Shift
- Signed Right Shift
- Unsigned Right Shift
- Logical NOT
- Logical AND
- Logical OR
- Multiply
- Divide
- Modulus
- Add
- Subtract
- Relational Operators
- Equal and Not Equal
- Identically Equal and Not Identically Equal
- Conditional Operator
- Assignment Operators
- Comma Operator