- Assignment Operators
- Arithmetic Operators
- Unary Operators
- Comparison Operators
- String Operators
- Logical Operators
All of the operators won’t be covered in this one tutorial since all we need are the essentials to get started with programming. Once we’ve reached a certain level of programming I will go into more details on the ones that have been left out.
The most basic assignment operator is the = sign which assigns the value on the right operand to the left. The other assignment operators that are listed below are considered shorthand.
var x = 3; // Assigns the value 3 to x x += 5; // The value of x will be 8 x -= 1; // The value will be 4
If the last two statement above confused you a little, it’s okay. The first statement assigns x the value of 3. On the statement below it we aren’t creating a new variable since there is no var in front of it. What we are doing instead is taking the value of x and adding 5 to it with the += operator which gives you the value of 8 in the end. Finally, the last statement takes the value of x, which is currently 8 and subtracts 1. That leaves x as 7.
var x = 2 + 5 // Adds 2 numbers which assigns&amp;amp;nbsp;7 to the variable x var y = 3 * 4 // Multiplies 2 numbers which assigns 12 to the variable y var z = 7 – 6 // Subtracts 2 numbers which assigns 1 to the variable z var a = 8 / 2 // Divides 2 numbers which&amp;amp;nbsp;assigns 4 to the variable a
Another operator is known as the modulus which is represented by the % symbol. What it does is divides the two operands and the remainder is the result.
var x = 11 % 5 // x is equal to 1 because the remainder here is 1
Unary operators only need a single operand, and it can be placed in front or behind the operator. They are pretty straight forward and great to use.
Let’s start by creating a variable with a value of 5.
var x = 5
Typically using the arithmetic operand, to add one you can simply write this:
x = x + 1; // Since x was initially 5 we added one to make it 6
It’s simple and it works! There’s another way of doing it though. An easier and quicker way. This is just a brief introduction and I will go into more detail about it in a later tutorial.
var x = 3; x = x + 1; // Equals 4 x++; // Equals 5
Since x started out as 3 we then added 1 to it to make it for. Then after that we used the unary operator ++ and added 1 to it again which then leaves x as 5. Now if you want to subtract one all you have to do is use the — operator instead.
x--; // Subtract one from the value of x.