← Back to course

Operators and Conditions

Operators and Conditions

Welcome back.

In the previous lesson, you learned variables and data types.

JavaScript can now remember things.

Very impressive.

Today we teach JavaScript how to make decisions.

This is where code becomes more interesting.

Until now, JavaScript could say:

“I know the price.”

Today JavaScript can say:

“If the price is too high, show a warning.”

That is a big step.

Programs are full of decisions:

JavaScript uses operators and conditions to decide what should happen.

Basically, today JavaScript starts judging situations.

Politely.

Mostly.

What You Will Learn

In this lesson, you will learn:

By the end of this lesson, JavaScript will be able to make basic decisions.

Small decisions.

Useful decisions.

Not life decisions.

Please do not let JavaScript choose your haircut yet.

Create the Project

Create a folder for this lesson:

mkdir javascript-lesson3
cd javascript-lesson3
touch index.html
touch script.js

Your project should look like this:

javascript-lesson3/
  index.html
  script.js

Open the folder in your editor.

We will use the console first.

Then we will show results on the page.

Step by step.

No chaos sprint.

Write the HTML

Open index.html and add this:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Operators and Conditions</title>
</head>
<body>
  <h1>Operators and Conditions</h1>
  <p>Open the browser console to see JavaScript output.</p>

  <script src="script.js"></script>
</body>
</html>

Open the file in your browser.

Open the console:

Now JavaScript is ready to calculate and judge.

A dangerous combination.

Arithmetic Operators

Arithmetic operators are used for math.

Example:

const a = 10;
const b = 3;

console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(a / b);

Output:

13
7
30
3.3333333333333335

Common arithmetic operators:

+   addition
-   subtraction
*   multiplication
/   division
%   remainder
**  exponentiation

Example:

const number = 10;

console.log(number % 3);
console.log(2 ** 3);

Output:

1
8

10 % 3 gives 1 because 10 divided by 3 leaves a remainder of 1.

2 ** 3 means 2 to the power of 3.

So:

2 * 2 * 2 = 8

JavaScript can do math.

Sometimes too honestly.

But it can do math.

Assignment Operators

You already know this:

let score = 10;

The = symbol assigns a value.

It does not mean “equals” like in math class.

It means:

“Put this value into this variable.”

Example:

let score = 10;

score = 20;

console.log(score);

Output:

20

You can also update values using shortcut operators:

let points = 10;

points += 5;
console.log(points);

points -= 3;
console.log(points);

points *= 2;
console.log(points);

points /= 4;
console.log(points);

Output:

15
12
24
6

These are shortcuts.

points += 5;

means:

points = points + 5;

Useful.

Short.

Less typing.

Your fingers approve.

Comparison Operators

Comparison operators compare values and return true or false.

Example:

const age = 18;

console.log(age >= 18);
console.log(age < 18);

Output:

true
false

Common comparison operators:

>    greater than
<    less than
>=   greater than or equal to
<=   less than or equal to
===  equal value and type
!==  not equal value or type

Example:

const price = 100;

console.log(price > 50);
console.log(price < 50);
console.log(price === 100);
console.log(price !== 200);

Output:

true
false
true
true

Comparison operators are the foundation of conditions.

They help JavaScript decide.

If the answer is true, do something.

If the answer is false, do something else.

Very useful.

Very judgmental.

The Difference Between = and ===

This is important.

Very important.

Do not skip this.

= assigns a value.

const age = 33;

=== compares a value.

console.log(age === 33);

Example:

const age = 33;

console.log(age === 33);
console.log(age === 40);

Output:

true
false

Do not write this inside a condition:

if (age = 33) {
  console.log("Age is 33");
}

That is assignment, not comparison.

Use this:

if (age === 33) {
  console.log("Age is 33");
}

One = means:

“Store this.”

Three === means:

“Compare this.”

This mistake is common.

JavaScript will not always save you.

JavaScript sometimes watches you fall and says:

“Interesting.”

Avoid == for Now

JavaScript also has ==.

Example:

console.log(5 == "5");

This returns:

true

Why?

Because == tries to convert values before comparing.

That can be confusing.

Use === instead.

Better:

console.log(5 === "5");

Output:

false

Why?

Because one value is a number and the other is a string.

For beginners, simple rule:

Use ===.

Use !==.

Avoid ==.

Your future debugging sessions will be shorter.

And your coffee will stay warmer.

if Statement

An if statement runs code only when a condition is true.

Example:

const age = 20;

if (age >= 18) {
  console.log("You are an adult.");
}

Output:

You are an adult.

Structure:

if (condition) {
  // code runs if condition is true
}

Example:

const isLoggedIn = true;

if (isLoggedIn) {
  console.log("Welcome back!");
}

The condition is true, so the message appears.

If the condition is false, the code inside the block does not run.

JavaScript is strict.

No true?

No action.

else Statement

else runs when the if condition is false.

Example:

const age = 16;

if (age >= 18) {
  console.log("You can enter.");
} else {
  console.log("You are too young.");
}

Output:

You are too young.

This means:

If age is greater than or equal to 18, show the first message.

Otherwise, show the second message.

JavaScript has now become a tiny door security guard.

With curly braces.

else if Statement

Use else if when you have more than two possibilities.

Example:

const score = 75;

if (score >= 90) {
  console.log("Excellent!");
} else if (score >= 60) {
  console.log("Good job!");
} else {
  console.log("Keep practicing.");
}

Output:

Good job!

JavaScript checks from top to bottom.

First condition:

score >= 90

False.

Second condition:

score >= 60

True.

So JavaScript runs that block and stops.

It does not continue checking after it finds a true condition.

Efficient.

Almost suspiciously efficient.

Logical Operators

Logical operators combine conditions.

Common logical operators:

&&   and
||   or
!    not

&& means AND

Both conditions must be true.

const age = 25;
const hasTicket = true;

if (age >= 18 && hasTicket) {
  console.log("You can enter.");
}

This means:

Age must be at least 18.

And the user must have a ticket.

Both.

No ticket?

No entry.

Even if the user gives JavaScript sad eyes.

|| means OR

At least one condition must be true.

const isAdmin = false;
const isEditor = true;

if (isAdmin || isEditor) {
  console.log("You can edit this page.");
}

This means:

If the user is admin OR editor, allow editing.

One true condition is enough.

JavaScript says:

“Good enough. Come in.”

! means NOT

! reverses a boolean.

const isLoggedIn = false;

if (!isLoggedIn) {
  console.log("Please log in.");
}

!isLoggedIn means:

“not logged in.”

Since isLoggedIn is false, !isLoggedIn becomes true.

This can feel strange at first.

But it is very useful.

It is JavaScript’s way of saying:

“Actually, the opposite.”

Build a Login Example

Replace script.js with this:

const userName = "Viktor";
const isLoggedIn = true;
const isAdmin = false;

if (isLoggedIn && isAdmin) {
  console.log(`Welcome admin ${userName}.`);
} else if (isLoggedIn) {
  console.log(`Welcome ${userName}.`);
} else {
  console.log("Please log in.");
}

Output:

Welcome Viktor.

Why?

So JavaScript shows the normal welcome message.

Good.

The user enters.

But not with admin powers.

No digital crown today.

Show Conditions on the Page

Now let us make a small product availability example.

Update index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Operators and Conditions</title>

  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 700px;
      margin: 60px auto;
      padding: 0 24px;
      background-color: #f3f4f6;
      color: #111827;
    }

    .card {
      background-color: white;
      padding: 24px;
      border: 2px solid #e5e7eb;
      border-radius: 18px;
    }

    .success {
      color: #15803d;
      font-weight: 700;
    }

    .warning {
      color: #b45309;
      font-weight: 700;
    }

    h1 {
      font-size: 42px;
    }

    p {
      font-size: 20px;
      line-height: 1.6;
    }
  </style>
</head>
<body>
  <h1>Operators and Conditions</h1>

  <div class="card">
    <h2 id="productName"></h2>
    <p id="productPrice"></p>
    <p id="productStatus"></p>
  </div>

  <script src="script.js"></script>
</body>
</html>

Now update script.js:

const productName = "JavaScript Course";
const price = 49;
const budget = 60;
const isAvailable = true;

const productNameElement = document.getElementById("productName");
const productPriceElement = document.getElementById("productPrice");
const productStatusElement = document.getElementById("productStatus");

productNameElement.textContent = productName;
productPriceElement.textContent = `Price: €${price}`;

if (isAvailable && price <= budget) {
  productStatusElement.textContent = "Good news! This product is available and fits your budget.";
  productStatusElement.className = "success";
} else if (isAvailable && price > budget) {
  productStatusElement.textContent = "The product is available, but it is over your budget.";
  productStatusElement.className = "warning";
} else {
  productStatusElement.textContent = "Sorry, this product is not available.";
  productStatusElement.className = "warning";
}

Refresh the browser.

You should see product information and a status message.

Try changing:

const budget = 30;

Then refresh.

Try changing:

const isAvailable = false;

Refresh again.

Now JavaScript shows different messages depending on the data.

That is real conditional logic.

Your page is no longer just showing information.

It is deciding what to show.

Tiny brain unlocked.

Common Mistakes

Using = Instead of ===

Wrong:

if (age = 18) {
  console.log("Adult");
}

Correct:

if (age === 18) {
  console.log("Adult");
}

One = assigns.

Three === compares.

Tattoo this on your developer soul.

Or just remember it.

Less painful.

Forgetting Curly Braces

Wrong:

if (isAvailable)
  console.log("Available");
  console.log("Buy now");

This can be confusing.

Use curly braces:

if (isAvailable) {
  console.log("Available");
  console.log("Buy now");
}

Curly braces make the block clear.

They are small.

They are curly.

They are important.

Conditions in the Wrong Order

Example:

const score = 95;

if (score >= 60) {
  console.log("Good");
} else if (score >= 90) {
  console.log("Excellent");
}

This prints:

Good

Why?

Because score >= 60 is true, so JavaScript stops there.

Better:

if (score >= 90) {
  console.log("Excellent");
} else if (score >= 60) {
  console.log("Good");
}

Check more specific conditions first.

JavaScript reads from top to bottom.

Like a very literal person.

Practice

Create variables:

Rules:

Example:

const userName = "Anna";
const age = 22;
const hasTicket = true;
const isVip = false;

if (isVip) {
  console.log(`Welcome VIP, ${userName}.`);
} else if (age >= 18 && hasTicket) {
  console.log(`${userName}, you can enter.`);
} else if (age < 18) {
  console.log(`${userName}, you are too young.`);
} else {
  console.log(`${userName}, you need a ticket.`);
}

Change the values and test all possible results.

Do not just read it.

Run it.

Break it.

Fix it.

JavaScript respects action.

Mostly.

Mini Challenge

Create a discount calculator.

Variables:

Rules:

Show the result on the page.

Use:

Bonus:

Add different CSS classes for success and warning messages.

This is a real-world pattern.

Prices.

Budgets.

Messages.

Conditions.

The web is basically this, but with more meetings.

Summary

Today you learned:

This is a major step.

Now your code can choose.

Not perfectly.

Not wisely every time.

But it can choose.

And that is how interactive applications begin.

Next Lesson

In the next lesson, we will learn functions.

Functions help you reuse code and avoid repeating yourself.

Because if you copy the same code ten times, JavaScript may run it.

But your future self will quietly cry.