Use Sophia to knock out your gen-ed requirements quickly and affordably. Learn more
×

Operators and Expressions

Author: Sophia

what's covered
In this lesson, you will learn how JavaScript uses operators to perform calculations, make comparisons, and combine conditions. Operators are the building blocks that transform static values into dynamic programs. Specifically, this lesson will cover the following:

Table of Contents

1. Arithmetic Operators

Once you have data stored in variables, the next step is using that data to solve problems. JavaScript operators make this possible by allowing you to perform calculations and create new values. Arithmetic operators allow you to perform mathematical calculations in JavaScript. These operators work with numeric values and return numeric results, making them essential for tasks like calculating totals or computing scores.

term to know
Arithmetic Operator
A symbol that performs mathematical calculations on numeric values, such as addition, subtraction, multiplication, division, or finding the remainder.

1a. Basic Math Operations

JavaScript provides several arithmetic operators that allow you to perform calculations. Most of these operators work in a familiar way, similar to basic math.

Each operation combines two values, called operands, and produces a result. Consider this expression:

let total = 25 + 17;

Here, the values 25 and 17 are operands, and the + operator combines them to produce 42.

Other arithmetic operators follow this same pattern.

EXAMPLE

let difference = 100 - 37; // subtraction
let product = 12 * 8; // multiplication
let average = 240 / 4; // division

One operator that works a little differently is the modulus operator (%), which often causes confusion.

Instead of giving the result of division, modulus returns the remainder.

You may remember this from long division:

space space space space space space 3 space straight R 2</dd></dl></dd></dl>
5 long division enclose 17 space space end enclose

This means 5 goes into 17 three times:

  • 5 cross times 3 equals 15
  • 17 minus 15 equals 2
The value left over (2) is the remainder.

The modulus operator returns just that remainder.

terms to know
Operand
A value that an operator acts upon.
Modulus
An operator (%) that returns the remainder after dividing one number by another.

1b. Increment and Decrement

JavaScript also provides shorthand operators for increasing or decreasing a value by one. These are useful when working with counters, such as tracking scores, loops, or quantities.

The increment operator (++) adds 1 to a variable, while the decrement operator (--) subtracts 1.

EXAMPLE

let count = 5;
count++; // count is now 6

let lives = 3;
lives--; // lives is now 2

These operators update the value directly, so you do not need to write expressions like count = count + 1. In most cases, you can place the operator after the variable, and it will behave as expected. However, the position of the operator can affect when the value is updated.

EXAMPLE

When the operator comes after the variable (postfix), JavaScript uses the current value first, then updates it.

let x = 5;
let y = x++; // y is 5, then x becomes 6

When the operator comes before the variable (prefix), JavaScript updates the value first, then uses it:

let a = 5;
let b = ++a; // a becomes 6, then b is 6

In many situations, this difference does not matter. It becomes important when the value is used as part of a larger expression.

try it
Consider the following code:

let score = 10;
score++;
score++;
let result = score % 4;
What is the value of result after this code runs?
The value of result is 0. Starting with 10, the increments make it 12. Then 12 % 4 equals 0 because 12 is evenly divisible by 4.

big idea
Arithmetic operators perform calculations using two operands. Increment (++) and decrement (--) are shorthand operators that adjust a single variable by one, with prefix and postfix forms affecting when the update occurs.

terms to know
Increment Operator
An operator (++) that increases the value of a variable by 1.
Decrement Operator
An operator (--) that decreases the value of a variable by 1.


2. Comparison Operators

Comparison operators allow you to compare two values to determine how they relate to each other. Instead of producing a number, these comparisons return a Boolean value, which is either true or false. Comparison operators are essential for decision-making in JavaScript. They are commonly used in conditional statements, such as determining whether a user is old enough to access a feature or whether a score meets a required threshold.

term to know
Comparison Operator
A symbol that evaluates the relationship between two values and returns a Boolean (true or false).

2a. Relational Operators

Relational operators compare two values to determine their order. They answer questions such as “Is one value greater than another?” or “Does this value meet a minimum requirement?”

EXAMPLE

let isSmaller = 5 < 10; // true

let isGreater = 20 > 25; // false

let isAtLeast = 18 >= 18; // true

let isAtMost = 5 <= 5; // true

The operators < and > compare whether a value is less than or greater than another. The operators <= and >= include equality, meaning the values can be equal and still return true.

term to know
Relational Operator
An operator that compares two values to determine their order, such as less than (<) or greater than or equal to (>=), and returns a Boolean (true or false).

2b. Equality and Inequality

While relational operators compare order, equality operators compare whether values are the same. JavaScript provides two ways to check whether values are equal: loose equality and strict equality. The key difference between them is how they handle data types. To understand this difference, recall how JavaScript handles type coercion.

recall
Type coercion is the automatic conversion of one data type to another. JavaScript sometimes performs this conversion when comparing values.

The loose equality operator (==) compares values after automatically converting them to the same type, meaning the values may be changed before the comparison. This can lead to unexpected results.

EXAMPLE

let result1 = 5 == "5"; // true (string converted to number)
let result2 = 0 == false; // true (false converted to 0)
In both cases, JavaScript changes one of the values before making the comparison.

The strict equality operator (===) compares both the value and the data type without making any conversions, so the values must already match exactly.

EXAMPLE

let result1 = 5 === "5"; // false (number vs string)
let result2 = 5 === 5; // true (same value and type)

The following diagram highlights the difference between loose and strict equality.

Comparison showing that loose equality performs type conversion before comparison, while strict equality compares both value and type without conversion.

key concept
Always prefer the strict equality operator (===) over the loose equality operator (==). Strict equality prevents unexpected type conversions that can cause bugs.

The inequality operators work similarly. The loose inequality operator (!=) returns true if values are not equal after a type conversion. The strict inequality operator (!==) returns true if values differ in value or type.

EXAMPLE

let notEqual1 = 5 != "5"; // false (equal after conversion)
let notEqual2 = 5 !== "5"; // true (different types)

try it
In this activity, you will test comparison operators using JavaScript.

1. Open your index.html file in Codespaces.

2. Add the following code inside your <script> element:

Copy
let a = 10 === "10";
let b = 15 > 15;
let c = 20 <= 20;

console.log(a);
console.log(b);
console.log(c);
3. Predict the output before running the code.

4. Save your file and open the browser preview.

5. Open the browser console and compare your predictions to the actual results.

6. Modify one of the comparisons and observe how the output changes.

terms to know
Loose Equality Operator
An operator (==) that compares two values after converting them to the same data type.
Strict Equality Operator
An operator (===) that compares two values for equality without converting their data types.


3. Logical Operators

Logical operators combine or modify Boolean values to create more complex conditions. Instead of evaluating a single comparison, they allow you to work with multiple conditions at once. You might want to check whether a user meets more than one requirement, such as being over a certain age and having a valid account. Logical operators make it possible to combine these checks into a single expression. Logical operators can also reverse a result. This allows you to take an existing condition and check for the opposite outcome. These operators are essential when building decision-making logic, especially in conditional statements where multiple criteria must be evaluated together. JavaScript provides three main logical operators: AND, OR, and NOT. Each one evaluates conditions in a different way.

The AND operator (&&) returns true only when all conditions are true.

EXAMPLE

let hasTicket = true;
let hasID = true;
let canEnter = hasTicket && hasID; // true

let isWeekend = false;
let isSunny = true;
let goPark = isWeekend && isSunny; // false

The OR operator (||) returns true when at least one operand is true.

EXAMPLE

let hasCash = false;
let hasCard = true;
let canPay = hasCash || hasCard; // true

The NOT operator (!) inverts a Boolean value.

EXAMPLE

let isLoggedIn = false;
let showLoginButton = !isLoggedIn; // true

Truth tables showing how AND, OR, and NOT operators evaluate Boolean values based on different combinations of true and false.

Logical operators are often used together to evaluate more complex conditions. For example, you might check whether a user meets multiple requirements at once.

EXAMPLE

let age = 25;
let hasLicense = true;
let hasInsurance = true;

let canRentCar = age >= 21 && hasLicense && hasInsurance; // true

When expressions like this include multiple conditions, JavaScript evaluates them step by step. In many cases, it does not need to evaluate every part of the expression before determining the result. This behavior is called short-circuit evaluation, which means JavaScript stops evaluating as soon as the result is known.

With AND (&&), if the first condition is false, the entire expression must be false, so JavaScript stops immediately.

With OR (||), if the first condition is true, the entire expression must be true, so JavaScript stops immediately.

EXAMPLE

let isActive = false;
let result = isActive && expensiveFunction(); // function never runs
let hasCachedData = true;
let data = hasCachedData || fetchFromServer(); // fetch never runs

key concept
Short-circuit evaluation allows JavaScript to stop processing early once the result is determined. This can improve performance and help prevent errors.

try it
In this activity, you will use Codespaces to evaluate a logical expression step by step.

1. Open your index.html file in Codespaces.

2. Locate the <script> element near the bottom of the file.

3. Add the following code inside the <script> element:

Copy
let isAuthenticated = true;
let isAdmin = false;
let hasPermission = true;

let canProceed = isAuthenticated && (isAdmin || hasPermission);

console.log(canProceed);
4. Predict the result before running the code.

5. Save your file and open the browser preview.

6. Open the browser console and view the output.

7. Evaluate the expression inside the parentheses first, then determine how the && operator affects the final result.
Click to reveal the answer.
The value is true. The expression inside the parentheses evaluates this first: isAdmin || hasPermission is true. Then isAuthenticated && true is true.

terms to know
Logical Operator
A symbol that combines or modifies Boolean values, including AND (&&), OR (||), and NOT (!).
Short-Circuit Evaluation
A behavior where JavaScript stops evaluating a logical expression as soon as the result is determined.


4. Building Expressions

An expression is a piece of code that combines values and operators to produce a result. Throughout this lesson, you have already been working with expressions when performing calculations, making comparisons, and combining conditions.

EXAMPLE

Each of the following is an expression:

5 + 3
score >= 70
isAuthenticated && hasPermission

When an expression includes multiple operators, JavaScript must determine the order in which each part is evaluated. This process follows a set of rules called operator precedence.

In general, JavaScript evaluates expressions in the following order:

  • Parentheses ()
  • Arithmetic operations
  • Comparison operators
  • Logical operators
Diagram showing the order of JavaScript operator precedence from highest to lowest, including parentheses, arithmetic, comparison, and logical operators.

EXAMPLE

let result = 5 + 3 * 2; // 11
Multiplication is evaluated before addition, so 3 * 2 becomes 6, and then 5 is added to produce 11.

To make expressions easier to read and control the order of evaluation, you can use parentheses.

let result = (5 + 3) * 2; // 16
Here, the parentheses force JavaScript to evaluate 5 + 3 first.

When expressions include multiple types of operators, JavaScript evaluates them step by step.

EXAMPLE

let score = 85;
let bonus = 10;
let passingScore = 70;

let passed = score + bonus >= passingScore && score <= 100;
Step-by-step breakdown of a complex expression showing how arithmetic, comparison, and logical operations are evaluated in sequence to produce a final result.

This expression is evaluated in stages:

  1. Arithmetic: 85 + 10 becomes 95.
  2. Comparison: 95 >= 70 is true, and 85 <= 100 is true.
  3. Logical: true && true is true.

try it
In this activity, you will evaluate a complex expression using JavaScript.

1. Add the following code to your <script> element in Codespaces:

Copy
let age = 17;
let hasParentConsent = true;
let minimumAge = 18;

let eligible = age >= minimumAge || (age >= 16 && hasParentConsent);

console.log(eligible);
2. Predict the result before running the code.

3. Save your file and open the browser console to view the output.

4. Evaluate the expression step by step to confirm your answer.

term to know
Expression
A piece of code that combines values and operators to produce a result.

summary
In this lesson, you learned how arithmetic operators perform calculations using basic math operations and how increment and decrement adjust values efficiently. You explored comparison operators, including relational operators that compare order and equality and inequality operators that determine whether values are the same. You then used logical operators to combine and modify conditions for more complex decision-making. Finally, you examined evaluating expressions to understand how JavaScript determines the order of operations and produces results.

Source: THIS TUTORIAL WAS AUTHORED BY SOPHIA LEARNING. PLEASE SEE OUR TERMS OF USE.

REFERENCES

Mozilla Developer Network. (n.d.). How the web works. developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/How_the_Web_works

Terms to Know
Arithmetic Operator

A symbol that performs mathematical calculations on numeric values, such as addition, subtraction, multiplication, division, or finding the remainder.

Comparison Operator

A symbol that evaluates the relationship between two values and returns a boolean (true or false).

Decrement Operator

An operator (--) that decreases the value of a variable by 1.

Expression

A piece of code that combines values and operators to produce a result.

Increment Operator

An operator (++) that increases the value of a variable by 1.

Logical Operator

A symbol that combines or modifies boolean values, including AND (&&), OR (||), and NOT (!).

Loose Equality Operator

An operator (==) that compares two values after converting them to the same data type.

Modulus

An operator (%) that returns the remainder after dividing one number by another.

Operand

A value that an operator acts upon.

Relational Operator

An operator that compares two values to determine their order, such as less than (<) or greater than or equal to (>=), and returns a boolean (true or false).

Short-Circuit Evaluation

A behavior where JavaScript stops evaluating a logical expression as soon as the result is determined.

Strict Equality Operator

An operator (===) that compares two values for equality without converting their data types.