JavaScriptLesson 3 of 10Jump to practice

Operators

Do math, join text, compare values and combine true-or-false checks.

An operator is a symbol that does something with values: adds them, compares them, joins them.

Math

Operator Meaning Example Result
+ Add 7 + 2 9
- Subtract 7 - 2 5
* Multiply 7 * 2 14
/ Divide 7 / 2 3.5
% Remainder 7 % 2 1
** Power 7 ** 2 49
Math in JavaScript
Open in editor
<script>
const price = 45;
const quantity = 3;
const total = price * quantity;
console.log("Total:", total);

console.log("Split between 4:", total / 4);
console.log("Is 17 even?", 17 % 2 === 0);

let points = 10;
points += 5;   // same as points = points + 5
points++;      // add 1
console.log("Points:", points);
</script>
Result

+=, -=, *= and /= are shortcuts: points += 5 means points = points + 5. points++ adds one.

Joining text

+ also joins strings. If either side is a string, the other side is turned into text first. That catches everyone at least once:

Plus with strings
Open in editor
<script>
console.log("Hello, " + "Emma");   // joins text
console.log("2" + 3);              // "23", not 5!
console.log(Number("2") + 3);      // 5
</script>
Result

Values typed into a form always arrive as strings. Use Number() before doing math with them.

Comparing

Comparisons give true or false.

Operator Meaning
=== Equal (same value and same type)
!== Not equal
>, < Greater than, less than
>=, <= Greater than or equal, less than or equal

Combining true and false

  • && (and): true only if both sides are true.
  • || (or): true if either side is true.
  • ! (not): flips true to false and false to true.
Logical operators
Open in editor
<script>
const age = 20;
const hasTicket = true;
const day = "Saturday";
const isRaining = false;

console.log("Can enter:", age >= 18 && hasTicket);
console.log("Weekend:", day === "Saturday" || day === "Sunday");
console.log("Dry outside:", !isRaining);
</script>
Result

You’ll use these all the time in the next lesson, to make decisions.

Practice

Check what you just learned. Fill in the missing code, then answer the quiz.

  1. Exercise 1

    Add 5 to score using the shorthand assignment operator.

    let score = 10;
    score  5;

  2. Exercise 2

    Check that age is exactly 18, without JavaScript converting types.

    console.log(age  18);

  3. Exercise 3

    Get the remainder when 10 is divided by 3.

    console.log(10  3); // 1

Quiz: 3 questions

1. What does "2" + 3 give?
2. Which of these is true?
3. What is true && false?

Finish the practice to complete this lesson.