/

HTML / CSS / JavaScript Tutorial

JavaScript Operator: plus

[this page | pdf | back links]

In JavaScript, the + operator has three possible meanings:

 

Arithmetic operator (binary)

 

Addition, e.g. if x is 8 then y = x + 2 results in y becoming 10

 

Arithmetic operator (unary)

 

Plus sign, e.g. if x is 8 then then +x represents -8

 

String operator (binary)

 

Concatenation, e.g. if x is "a" then y = x + "b" results in y becoming "ab"

 

Further comments

 

If an expression involves ‘adding’ a string to a number then the number is coerced to a string and string concatenation is applied.

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>table,th,tr,td {border: 1px solid black;
  border-collapse: collapse;}</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="ArithmeticAdditionExample"></code></td>
<td><code id="ArithmeticAddition"></code></td>
</tr>
<tr>
<td><code id="ArithmeticPlusExample"></code></td>
<td><code id="ArithmeticPlus"></code></td>
</tr>
<tr>
<td><code id="StringPlusExample"></code></td>
<td><code id="StringPlus"></code></td>
</tr>
<tr>
<td><code id="MixedPlusExample"></code></td>
<td><code id="MixedPlus"></code></td>
</tr>
</table>

<script>
document.getElementById("ArithmeticAdditionExample").innerHTML =
  'var x = 3 + 4;';
document.getElementById("ArithmeticAddition").innerHTML = 3 + 4;
document.getElementById("ArithmeticPlusExample").innerHTML =
  'var x = +3;';
document.getElementById("ArithmeticPlus").innerHTML = +3;
document.getElementById("StringPlusExample").innerHTML =
  'var x = "a" + "b";';
document.getElementById("StringPlus").innerHTML = "a" + "b";
document.getElementById("MixedPlusExample").innerHTML =
  'var x = ("3" + 1) + 4;';
document.getElementById("MixedPlus").innerHTML = ("3" + 1) + 4;
</script>

</body>
</html>


NAVIGATION LINKS
Contents | Prev | Next | JavaScript Operators


Desktop view | Switch to Mobile