Operators allow you to tell your script exactly how a piece of data should interact with another piece of data. For example, if you wanted to add 2 pieces of data, then you would use the plus sign ( + ) operator. Here’s how that would look like.
5 + 5
There are many kinds of operators such as math operators, assignment operators, and comparison operators. Let’s take a look at each of these.
var num1 = 3 + 3; // Addition
var num2 = 3 - 3; // Subtraction
var num3 = 3 / 3; // Division
var num4 = 3 * 3; // Multiplication
var num5 = 4 % 3; // Modulus
You should be familiar with all these operators. The only operator that you may not know about is the modulus math operator. This is the very last operator used in our code. It’s represented by the % sign.The value that is returned is the remainder. For example, if you divide 3 by 3, you get 0. However, if you divide 4 by 3, you get 1 with a remainder of 1. You’re returned the remainder 1. We’ll learn how this can be useful in a future tutorial.
You’ve already used an assignment operator. It’s the equal sign ( = ). Assignment operators allow you to set a value for a certain variable. There are a couple of other assignment operators you could use.
Here are examples of them.
var num6 = 3;
num6 += 3; // 6 : Addition
num6 -= 3; // 3 : Subtraction
num6 /= 3; // 1 : Division
num6 *= 3; // 3 : Multiplication
num6 %= 3; // 0 : Modulus
You’ll notice that we’re using the math operators combined with the assignment operators. This is simply a shortcut. If you’re manipulating the current value of a variable with a new value, then you can use this as a shortcut.
You just type in the math operator before the assignment operator to do so. In the example above, there’s a variable named num6 with the initial value of 6. The next line adds 3 to the current value resulting in 6.
Adding Strings Together
You can also add strings together like so.
var add_string = 'This is a ' + 'string'; // This is a string
var num_string = 'This is a ' + 5; // This is a 5
When you add these 2 strings together. You get 1 combined string. If you try adding a number and a string together, you’ll get back a string. This technique is calling appending. We’re appending 1 string onto another string to make one bigger string.
We haven’t talked about comparison operators yet. We will in a future tutorial when we talk about conditional statements. You’ll find yourself using operators everyday.