Operators
This lesson is part of the Web Programming 1 Course.
If you've ever used a calculator to do an operation such as adding numbers, then you've already used operators. And you probably already know about most of the operators that we'll cover in this lesson.
Operators are characters that allow you to do operations. If you want your program to add two numbers, then you can do so by using the addition operator, which is the plus sign (+). We'll dive into the other operators used for arithmetic in just a moment.
We have already talked about two very important operators in JavaScript. The first one was the equals sign (=) which you use to initialize a variable, or assign a new value to a variable that has already been initialized. This is known as the assignment operator. In the last lesson, you learned about the equality operator (==), which is used compare two values to see if they are equal.
Operators can be divided into the following categores:
Arithmetic Operators
Here are the operators that you can use to do arithmetic. Luckily, you probably already know most of them, except for maybe the 'modulus' operator:
+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (modulus)
I assume that you already know how arithmetic operators work in math, so we don't need to talk about them. Although, we should discuss the modulus operator, which is used to calculate the remainder when doing division operations, like so:
let remainder = 7 % 2; // divides 7 by 2 and returns the remainder
console.log(remainder); // the console log will show 1
The arithmetic operators require a value to be on each side. These values are known as operands. In a moment you'll see that some operators work with just a single operand.
Short-cut Arithmetic Operators
In programming languages there are shortcuts for doing arithmetic operators. As a beginner, these operators may just confuse you at first, but as you become more experienced you'll get comfortable with them.
Here are the short-cut arithmetic operators:
+= (for adding a number to a variable that's storing a number)
-= (for subtraction a number from a variable that's storing a number)
/= (for dividing a variable by another number)
*= (for multiplying a variable by another number)
Hopefully these will make more sense when you see how they are used in code:
let a = 4;
a += 2; // same as: a = a + 2;
console.log(a); // a is 6
let b = 4;
b -= 2; // same as: b = b - 2;
console.log(b); // b is 2
let c = 4;
c *= 2; // same as: c = c * 2;
console.log(c); // c is 8
let d = 4;
d /= 2; // same as: d = d / 2;
console.log(d); // d is 2
Concatenating Strings
The addition operator has another purpose in JavaScript. Not only can it be used for adding numbers, it can also be used for concatenating strings.
const str1 = "Hi";
const str2 = "there";
console.log(str1 + " " + str2);
You can also use the the short-cut addition operator to concatenate to a string variable:
let str = "Hello";
str += " World";
str += "!";
console.log(str); // logs "Hello World!"
You'll see the += operator used a lot to concatenate to a string variable.
The Increment and Decrement Operators
In programming, it's very common to increase or decrease a number variable by 1. You can use these operators to do so:
++ increases a number variable by one
-- decreases a number variable by one
Here's a code sample to demonstrate them:
let x = 5;
x++; // increases x by 1
console.log(x); // logs 6
x--; // decreases x by 1
console.log(x); // logs 5
The increment and decrement operators are known as unary operators, because unlike the other operates we've seen, they require just one operand.
Also note that you could easily use one of the previously discussed operators to increment or decrement a variable by one. But, as mentioned, it' such a common task to increment/decrement variables that these operators come in handy to keep your code concise.
We'll be seeing these operators used a lot when we talk about loops in a future lesson.
Comparison Operators
Comparison operators are used to compare two values. You can use in boolean expressions, and we've already used a few in our IF statements from the previous lesson.
Here are the most of the comparison operators:
< (less than)
> (greater than)
<= (less than or equal)
>= (greater than or equal)
== (equality operator)
!= (inequality operator)
There are a few more comparison operators, but we won't worry about them at this time.
Here is an IF statement in which the boolean expression is used to see if the value of x is greater than or equal to 5:
if(x >= 5){
console.log("It's true!");
}
The Equality Operator
Remember from the last lesson that a single equals sign is the assignment operator, and is used to assign a value to a variable. To see if two values are the same, we use the equality operator, which is two equals signs next to each other (==).
This IF statement checks to see if x is storing a value of 5:
if(x == 5){
console.log("TRUE!");
}else{
console.log("FALSE!");
}
You can use the equality operator to compare strings as well as numbers, but remember that JavaScript is case-sensitive.
const guess = prompt("Guess what word I'm thinking of.");
if(guess == "operators"){
alert("Good guess!");
}
Comparing for Inequality
Sometimes you'll want to compare values to see it they are NOT equal. In that case you can use the inequality operator, which is !=.
const myName = "Bob";
const yourName = prompt("What is your first name?");
if(myName != yourName){
alert("We have different names!");
}
Logical Operators
You can use the following logical operators to combine two or more boolean expressions.
&& (the AND operator)
|| (the OR operator)
The AND operator is two ampersands (&&), it allows you to see if two boolean expressions are both true. Here's an example:
let testScore1 = 95;
let testScore2 = 72;
if(testScore1 > 90 && testScore2 > 90){
console.log("Great job on both tests!")
}
The OR operator is two 'pipe' characters (||), it allows you to see if just one of two boolean expressions are. Here's an example:
if(testScore1 > 90 || testScore2 > 90){
console.log("Great job on ONE of the tests!")
}else{
console.log("Sorry, you didn't get an A on either test!")
}
The && and || operators are so commonly used in programming that I decided to include a few extra examples of each. We'll be talking about them in class!
This sample shows how you can determine if a number value falls within a range:
const number = prompt("Enter a number");
const min = 1;
const max = 10;
if(number >= min && number <= max){
console.log("In range!");
}else{
console.log("Out of range!")
}
This sample program suggests what to do based on the weather conditions:
const temperature = 75;
const raining = true;
const whatToDo;
if(temperature < 60 || raining){
whatToDo = "stay home";
}else{
whatToDo = "play golf";
}
console.log("Let's " + whatToDo);