/

HTML / CSS / JavaScript Tutorial

JavaScript Operator: plus assignment

[this page | pdf | back links]

In JavaScript, the += operator is the assignment operator with addition (if arithmetic) or concatenation (if string).

 

Arithmetic operator

 

For example, if x is 5 and y is 8 then y += x results in x remaining 5 and y = y + x, so y becomes 13.

 

String operator

 

For example, if x is "a" and y is "b" then y += x results in x remaining "a" and y = y + x, so y becomes "ba".

 

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>
<th>Resulting value of <code>y</code></th>
</tr>
<tr>
<td><code id="ArithmeticExample"></code></td>
<td><code id="Arithmeticx"></code></td>
<td><code id="Arithmeticy"></code></td>
</tr>
<tr>
<td><code id="StringExample"></code></td>
<td><code id="Stringx"></code></td>
<td><code id="Stringy"></code></td>
</tr>
</table>

<script>
document.getElementById("ArithmeticExample").innerHTML = 
  'var x = 5;<br>' +
  'var y = 8;<br>' +
  'y += x;';
var x = 5; var y = 8; y += x;
document.getElementById("Arithmeticx").innerHTML = x;
document.getElementById("Arithmeticy").innerHTML = y;

document.getElementById("StringExample").innerHTML = 
  'var x = "a";<br>' +
  'var y = "b";<br>' +
  'y += x;';
x = "a"; y = "b"; y += x;
document.getElementById("Stringx").innerHTML = x;
document.getElementById("Stringy").innerHTML = y;
</script>

</body>
</html>


NAVIGATION LINKS
Contents | Prev | Next | JavaScript Operators


Desktop view | Switch to Mobile