Operators
JavaScript Operators
JavaScript Operators are pretty standard. They are exactly what you would expect from your high school math class. Operators are anything you use when comparing or acting upon with numbers/values.
Arithmetic Operators
<html>
<body>
<script type="text/javascript">
var y = 7; // Setting our variable
var x = y + 2; // Addition, x would equal 9 here
var x = y - 2; // Subtraction, x would equal 5
var x = y * 2; // Multiplication, x would equal 14
var x = y / 4; // Division, x would equal 1.75
var x = y % 3; // Modulus (Division Remainder), x would equal 1
</script>
</body>
</html>
Incrementing and Decrementing Operators
Incrementing is adding 1, while decrementing is subtracting 1.
<html>
<body>
<script type="text/javascript">
var w = 0;
var x = 0;
var y = 0;
var z = 0;
document.write("w++ = " + w++);
document.write("<br/>");
document.write("x-- = " + x--);
document.write("<br/>");
document.write("++y = " + ++y);
document.write("<br/>");
document.write("--z = " + --z);
</script>
</body>
</html>
Result
w++ = 0
x-- = 0
++y = 1
--z = -1
Combining Strings
Let’s clear up how strings can be combined using JavaScript:
<html>
<body>
<script type="text/javascript">
var string1 = "You are awesome, ";
var string2 = "and you know it.";
var string3 = string1 + string2;
document.write(string3);
</script>
</body>
</html>
Result
You are awesome, and you know it.
Assignment Operators
Assignment operators are not a necessity for programmers, but they are great shortcuts.
<html>
<body>
<script type="text/javascript">
var x = 4;
var y = 2;
x = y; // x = 2
x += y; // x = 6, (same as x = x + y)
x -= y; // x = 2, (same as x = x - y)
x *= y; // x = 8, (same as x = x * y)
x /= y; // x = 2, (same as x = x / y)
x %= y; // x = 0, (same as x = x % y)
</script>
</body>
</html>