JavaScript Operators

This tutorial is part of a web programming course for people who have no programming experience.


I breifly mentioned the assignment operator and the equality operator in the previous lesson, but there are many others in JavaScript. They can be grouped into categories and we'll review each one below.

Arithmetic Operators

Arithmetic operators are used to perform math, and most of them will be familiar to you. Here they are:

+
Addition
-
Subtraction
*
Multiplication
/
Division
%
Modulus

I assume that you already know how arithmetic operators work in math, so we don't need to talk much about them. Although, there is one that may need some explanation, the modulus operator.

The Modulus Operator

The modulus operator is used to determine the remainder when doing division operations.

// The Modulus Operator (finds the remainder)
var remainder = 7 % 2;
console.log(remainder); // the console log will show 1

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 get more experience you'll become more comfortable with them.

Here are the short-cut arithemtic operators:

+=
Addition
-=
Subtraction
*=
Multiplication
/=
Division

These operators allow you to write more concise code, but you could just as easily use the long-hand version and your program will run exactly the same. They say that good programmers are lazy, and will take any short cut they can, so if you surf the web for code samples you'll see that these shortcuts are very common.

var x = 3;

x += 2;     //same as x = x + 2
x -= 2;     //same as x = x - 2
x /= 2;     //same as x = x / 2
x *= 2;     //same as x = x * 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 joining strings together. In programming, joining strings together is known as concatenating. You will be hearing this term a lot in your programming career.

var str1 = "Hi";
var str2 = "there";
console.log(str1 + " " + str2);

You can also use the the short-cut addition operator when concatenating strings. Here's an example:


var longMessage = "This is going to be a really long string, ";
longMessage += "and it might wrap a few lines of code, ";
longMessage += "so I decided to use the short-cut arithmetic operator ";
longMessage += "to demonstrate how you can use it to concatenate really long strings.";

console.log(longMessage);

Instead of trying to fit all that jibberish into one single statement, I spread them out into multiple statements and used the short-cut arithmetic operator to concatenate them.

The Increment and Decrement Operators

In programming, it's very common to increase or decrease a variable by 1. You could use these approaches:

var x = 1;
x = x + 1;  // this will increment x by 1
x += 1;     // this will also increment x by 1

But it's so common to increase or decrease a number by 1, two operators were created solely for this purpose:

++
Increment
--
Decrement

The increment and decrement operators are also another type of short-cut operator. They simply increase, or decrease a value by one.

var x = 7;

x++; 
console.log("The value of x is " + x);

x--;
console.log("The value of x is " + x);

Note that you could easily use the long-hand version, but you'll soon find out that incrementing and decrementing a variable by one is a very common task (especially when we start talking about loops). So the increment and decrement operator come in quite handy, and you'll find that they are commonly used by programmers.

Comparison Operators

You can use comparison operators in boolean expressions. You have probably already seen many of these operators in math, so we'll just discuss a few of them.

<
Less Than
>
Greater Than
<=
Less Than Or Equal
>=
Greater Than Or Equal
==
Equality
!=
Inequality
===
Strict Equality

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("x is greater than or equal to 5!");
}

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:  ==.

if(x == 5){
  console.log("Yes it's true, x is equal to 5!");
}else{
   console.log("x is NOT equal to 5!"); 
}

You can use the equality operator to compare strings as well as numbers, but remember that JavaScript is case-sensitive.

var 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 !=.

var myName = "Bob";
var yourName = prompt("What is your first name?");

if(myName != yourName){
  alert("We have different names!");
}

Logical Operators

You can use logical operators to combine two or more boolean expressions.

&&
AND
||
OR

The AND operator (&&)

The 'and' operator is two ampersands (&&), it allows you to see if two boolean expressions are both true. For example, if you wanted to see if a number stored in a variable is between two other numbers, you could use the 'AND' opertator:.

var x = 7;
var min = 1;
var max = 10;

if(x >= min && x <= max){
  console.log( x + " is within " + min + " and " + max);
}

When you combine two boolean expressions by using the AND operator, the final result will be true only if both expressions are true.

The OR operator ( || )

If you use the OR operator to combine two boolean expressions in an IF statement, the final result will evaluate to true if either of the boolean expressions is true.

var temperature = 75;
var rain = true;
var whatToDo;

if(temperature < 60 || rain){
    whatToDo = "stay home";    
}else{
    whatToDo = "play golf";
}

console.log("Let's " + whatToDo);

It might look a little funny that the second boolean expression in the above IF statement is simply the variable 'rain'. But note that a variable all by itself is actually an expression, and it must be evaluated in order to determine the result of the entire expression. In this case the 'rain' variable evaluates to true because it was initialized to true before the IF statement.

Here's another example:

var joeLikesProgramming = true;
var bettyLikesProgramming = false;
var sallyLikesProgramming = true;

if(joeLikesProgramming && sallyLikesProgramming){
  console.log("Joe AND Sally like programming!");
}

if(bettyLikesProgramming || sallyLikesProgramming){
  console.log("Betty OR Sally likes programming!");
}
NEXT LESSON: More on IF Statements and Operators