1

Lesson 3: Operators in JavaScript

In this lesson, we will explore various operators in JavaScript. Operators are symbols that perform operations on variables and values. They are essential in programming as they allow us to manipulate data.

Types of Operators

1. Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations:

  • + (Addition): Adds two values.
  • - (Subtraction): Subtracts one value from another.
  • * (Multiplication): Multiplies two values.
  • / (Division): Divides one value by another.
  • % (Modulus): Returns the remainder of division.
  • ++ (Increment): Increases the value by 1.
  • -- (Decrement): Decreases the value by 1.

Example of Arithmetic Operators:

      let x = 10;
      let y = 5;
      let sum = x + y; // 15
      let diff = x - y; // 5
      let prod = x * y; // 50
      let quotient = x / y; // 2
      let remainder = x % y; // 0
              

2. Comparison Operators

Comparison operators compare two values and return a boolean result (true or false):

  • ==: Equal to
  • ===: Strictly equal to (checks value and type)
  • !=: Not equal to
  • !==: Strictly not equal to
  • >: Greater than
  • >=: Greater than or equal to
  • <: Less than
  • <=: Less than or equal to

Example of Comparison Operators:

      let a = 10;
      let b = 20;
      console.log(a == b); // false
      console.log(a != b); // true
      console.log(a > b); // false
              

3. Logical Operators

Logical operators are used to combine or negate boolean expressions:

  • && (AND): Returns true if both operands are true.
  • || (OR): Returns true if either operand is true.
  • ! (NOT): Reverses the boolean value.

Example of Logical Operators:

      let isTrue = (10 > 5) && (5 > 2); // true
      let isFalse = (10 < 5) || (5 < 2); // false
      let negation = !(10 > 5); // false
              

4. Assignment Operators

Assignment operators are used to assign values to variables:

  • =: Assigns a value to a variable.
  • +=: Adds and assigns a value.
  • -=: Subtracts and assigns a value.
  • *=: Multiplies and assigns a value.
  • /=: Divides and assigns a value.

Example of Assignment Operators:

      let x = 10;
      x += 5; // x = 15
      x -= 3; // x = 12
              

Assignment

Write a program that performs the following operations:

  1. Add two numbers and display the result.
  2. Compare two numbers and display whether they are equal.
  3. Use logical operators to check multiple conditions and display the result.