Introducing operators

You’ll get familiar with JavaScript's operators. Assignment operators, arithmetic operators, comparison operators, logical and conditional operators...

This is another chapter of my old, unfinished book, ‘JavaScript Class’.


You’ll get familiar with operators really soon, that’s because you already know the basics of them. Yes, you do. You learned about them in your first years of elementary school. Addition, subtraction, multiplication, division… this is what operators are all about.

You will learn how to use the following operators:

  • Assignment
  • Arithmetic
  • Comparison
  • Logical
  • Conditional
  • String

Assignment

Assignment operators are used to assign values. A frequently used assignment operator is ‘=’ (equal). Let’s see how we can assign the integer value of 5 to variable x.


x = 5;



Well, that was certainly simple. You remember this from your first math hours.

You can also modify the value of the variable by adding to that variable another one. For example, we want to add to x, which has the value 4, variable y, which has the value 8.


x = 4; // assign to var x, value 4
x = 8; // assign to var y, value 8
x = x + y; // assign to x the result value of adding x with y



We just added x with y and assigned the value back to x. After this easy operation, x holds the value 12 (4+8). To put it more simple, if we replace the variables with the values they hold, we see exactly how the computer makes the operation:


x = 4 + 8;



We can do this with any arithmetic operation allowed in JavaScript.


x = 4; // assign to var x, value 4
y = 8; // assign to var y, value 8
x = x â€“ y; // result is -4
x = x * y; // result is 32
x = x / y; // result is 0.5



We can also add a value to a variable and assign it to another:


x = y + 3



If we consider, like in the earlier example, x to be 4, and y to be 8, the result will be 11 (8+3), because the earlier value of x is being reset.


x = 4; // assign to var x, value 4
y = 8; // assign to var y, value 8
x = y + 3; // Value of x is being reset to 11, the result of y + 3 (8 + 3)



And the rest arithmetic operators allowed by JavaScript can be used. You’ll find out what they do, and what are they used for in the following chapters.

Now it’s time to adventure deeper and see some how we can make the assignment operations abridged. Nevertheless, be sure you understand this lesson until now because abridged operators may be confusing to understand.
There is a short form of writing x = x + y. This is x+=y.
Confused? It’s very simple actually. There isn’t more to explain about this, because it’s just a short form. You may use it or not. Most programmers use it. Here is a useful table with all the operators that can be abridged, and how.

In the left part you have the abridged version, in the right the lengthen one.

x += y is x = x + y
x -= y is x = x - y
x *= y is x = x * y
x /= y is x = x / y
x %= y is x = x % y
x <<= y    is x = x << y
x >>= y    is x = x >> y 
x >>>= y is x = x >>> y 
x &= y is x = x & y 
x ^= y is x = x ^ y 
x |= y is x = x | y 



You probably don’t understand all the operators listed here, but they will be described in the next lessons.

Now let’s use the short form with our earlier script:


x = 4; // assign to var x, value 4
y = 8; // assign to var y, value 8
x -= y; // result is -4 and it’s stored in x
x *= y; // result is 32 and it’s stored in x
x /= y; // result is 0.5 and it’s stored in x



The results are the same as the lengthen version, but easier to write, and maybe even to understand for an advanced programmer who is used to the abridged version.

Also if you want to add to the current ‘x’ value, another value… let’s say 3, it’s better to do it like this:


x = 4; // assign to var x, value 4
x += 3 // 4 + 3 â€“ after this x is equal to 7



than the lengthen version, who would have looked like this:


x = 4; // assign to var x, value 4
x = 3 + 4 // 4 + 3 â€“ after this x is equal to 7

Arithmetic

You have used arithmetic operators in elementary school all the time. Addition, subtraction, multiplication, division… you know all of this. In JavaScript (and in many other languages) addition sign operator is +, subtraction sign is -, for multiplication you use * (asterisk) and for division / (slash). Let’s see the most common arithmetic operators in a simple table:

Operator Sign
———————
Addition +
Subtraction –
Multiplication *
Division /

In the following lines, you will see some examples uses of operators.


x = 4 + 2 // x will hold the value 6 after this

x = x + 1 // x will be incremented by 1, and will be 7

y = x - 1 // y will hold the value of x - 1, that is 6
z = x * y // z will hold the value resulted by the multiplication of x value (7) to y value (6), that is 7 * 6 = 42

q = z / 2 // divide value hold by z (42) and store it in q. Result is 42 / 2 = 21



You saw in the above examples that we added 1 to x, and stored it back in x, we incremented value of x by one. You often need to increment or decrement variable values by one, especially in loops (you will find out what this are in the following chapters of this book). Therefore, just like in the previous lesson, there is a short form for incrementing a variable value by one:

++x // this is the same as x = x + 1
--x // this is the same as x = x â€“ 1



Let’s assign a value to variable x and see what happens to it after it’s incremented and decremented:

x = 5
++x // var x is now 6
--x // var x is now 5



There are two types of incrementing, pre-increment and post-increment. In the above examples, we used pre-increment operators, because they were put in the front of the variable. Post-increment variables are put after the variable:

x = 5
x++ // var x is now 6
x-- // var x is now 5



Well, you probably think that they do the same thing… wrong. But I don’t blame you because you can’t understand the difference till you learn the loops, where post-increment and pre-increment do make a difference. For now let’s just say that pre-increment always increments the value once, no matter if the condition is false from the beginning, and post-increment never increments the value if the condition is false from the beginning. Don’t worry if it sounds confusing, we will come back at this when I will teach you JavaScript loops.
It’s time to complete the earlier table with these new operators:

Operator Sign
———————
Addition +
Subtraction –
Multiplication *
Division /
Increment ++
Decrement —

The last unary operator is the negation operator. It’s simple to understand. If we have a variable that holds a value, negating the variable will negate the value.


x = 4 // assigned 4 to variable x
-x // now x holds number -4



The operator looks the same as the subtraction operator, but when it’s used like this, in the front of a variable, it is considered a negation operator. Here’s our table till now, there is one operator left:


Operator Sign
———————
Addition +
Subtraction –
Multiplication *
Division /
Increment ++
Decrement —
Negation –


There is one operator left, the only binary arithmetic operator, modulus (%), or remainder. These operator calculates the remainder of two integers in a division operation.


11 % 3 = 2 // because 11 / 3 = 3 and remainder 2



If you didn’t understand the above example, I will explain it more exhaustive. We divide 11 by 3 (11 / 3). This division doesn’t return an integer, it returns 3,6666666666666666666666666666667, a floating number. Therefore, the computer finds a different number instead of 11, a smaller one, which will divide exactly by 3. The following smallest number after 11 is 10, but it’s not good, because still doesn’t divide by 3. Next number is 9, and it divides by 3, 9 divided by 3 resulting 3. The difference between our first number that didn’t exactly divide, 11, and the smallest number below 11 is what modulus returns: 11 – 9 = 2. The remainder is 2.
If we had division terms that would divide exactly, returning an integer, the modulus would return remainder 0. Let’s say that we had 9 divided by 3 in the first place, modulus operation and result would look like this:


9 % 3 = 0



This is our final arithmetic operators table:

Operator Sign
———————
Addition +
Subtraction –
Multiplication *
Division /
Increment ++
Decrement —
Negation –
Modulus %

Comparison

In programming you will often compare two or more values, and depending on the result you get, the script will take a decision. By comparing two terms like this:


4 < 6



we can only get one result, true or false… in this case the result is ‘true’. 4 can only be smaller or bigger than 6, it can’t be equal.
If it is to compare two numbers to see if they are equal, we can do it like this:


5 == 5



We can’t use the usual ‘=’ (equal) sign because it is already assigned for declaring variables. Therefore, for testing equality, we use two equal signs (==).
In this case, the result can be true or false, again. If the numbers are equal, “5==5” will return true, if not the returned result will be false. Of course, 5 equals 5 and the result is ‘true’.

What if we want to test for non-equality? If x is equal to y, the returned result to be false, and if x is not equal to y, the returned result to be true. How can we do that? Like this:


5 != 5



If x (5) and y (5) are not equal, the result returned will be true. This is somehow the reverse of ‘==’. In our case, the returned result will be false, because 5 is equal to 5.

In the following expression:


7 < 7



the returned value will be false, because 7 is not smaller than 7… it is equal. However, there is the ‘<=’ operator that returns true if the left term is smaller or equal to the right term. Therefore, while “7 < 7” return false,


7 <= 7



returns true, because it also accepts the possibility of the left term being equal to the right term.
The


7 >= 7



works the same, but it returns true when the left member is bigger or equal to the right member.

It’s time to see a table with all the comparison operators:

Operator Sign
————————————-
Equal to… ==
Not equal to… !=
Less than… <
Less than or equal to… <=
Greater than… >
Greater than or equal to… >=

Logical

Logical operators are similar to the comparison operators, and comparison operators are usually used with logical operators.
Logical operators compare the result of an expression and return ‘true’ or ‘false’.

The easiest way for you to understand logical operators is to see some examples.

The simplest logical operator is the NOT (or negation) operator. It returns true only if the term evaluated has the value 0.
For example


var x = 0;
!x;



will return true. Any other value except 0 will return false.

For understanding the ‘AND’ operator, let’s see the following example:


x > 5 && y < 10



If x is bigger than 5, and y is smaller than 10, the expression will return ‘true’. If x is bigger than 5 and y is bigger than 10, the expression will return ‘false’. Vice versa, if x is smaller than 5 and y is smaller than 10, the expression will return ‘false’.
That means that the expression will return true only if both comparisons return true.

For understanding the ‘OR’ operator we will use an example similar to ‘AND’:


x > 5 || y < 10



This returns true if only one of the comparison returns true. If none of the comparisons returns true, than the expression returns false. If both comparisons return false, than the expression returns false.


Operator    Sign
---------------------
NOT        !
AND        &&
OR        ||

Conditional

There are only two conditional operators. They act similar to the ‘if – else’ instruction (the ‘if – else’ instruction will be covered in the following chapters).
The ‘?’ and ‘:’ conditional operators are used together.
Let’s see an example of how this conditional operators act:


x <= y ? â€œX is smaller or equal to Y” : â€œX is bigger than Y”



The first expression is a comparison expression:


x <= y



The following is the ‘?’ conditional operator which tells the interpreter a condition is coming.
If X is smaller or equal to Y, the first string, before the “:” will be displayed:

X is smaller or equal to Y

If X is bigger than Y, the second string will be displayed, the one after the “:”:

X is bigger than Y

An easy method to do a little comparison and make a decision based on the result of the comparison.

Let’s review. If the expression before the ‘?’ operator returns true, the first option will be executed, the one before the ‘:’. If the expression returns false, the second option will be executed, the one after the ‘:’. We can write it like this, for a better understanding.


condition ? if_true : if_false

String

You can compare strings using the comparison operators about which you learned above and an extra operator, the concatenating operator.
The concatenate operator can be used to concatenate two or more strings. ‘+’ (plus) sign is used for string concatenating:


”This is â€œ + â€œa string”

will return

”This is a string”

Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top