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>
  
Click to view the demo

Rules for add operator:

Operand 1Operand 2Result
NaNany valueNaN
any valueNaNNaN
InfinityInfinityInfinity
-Infinity-Infinity-Infinity
Infinity-InfinityNaN
+0+0+0
-0+0+0
-0-0-0
stringstring, string concatenation
stringany valueother 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>
  
Click to view the demo

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>
  
Click to view the demo

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>
  
Click to view the demo
Home 
  JavaScript Book 
    Language Basics  

Operators:
  1. JavaScript Operators
  2. Increment/Decrement Operators
  3. Increment/Decrement Operators for String, Boolean, Floating-point and Object
  4. Unary Plus and Minus
  5. Bitwise Not operator
  6. Bitwise AND
  7. Bitwise OR
  8. Bitwise XOR
  9. Left Shift
  10. Signed Right Shift
  11. Unsigned Right Shift
  12. Logical NOT
  13. Logical AND
  14. Logical OR
  15. Multiply
  16. Divide
  17. Modulus
  18. Add
  19. Subtract
  20. Relational Operators
  21. Equal and Not Equal
  22. Identically Equal and Not Identically Equal
  23. Conditional Operator
  24. Assignment Operators
  25. Comma Operator