JavaScript Operators

Operators in JavaScript are symbols or keywords used to perform operations on variables and values. They are categorized based on their functionality, such as arithmetic, assignment, comparison, logical, and more.

Key Topics

Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations such as addition, subtraction, multiplication, and division.

let a = 10;
let b = 5;
console.log("Addition: ", a + b);
console.log("Subtraction: ", a - b);
console.log("Multiplication: ", a * b);
console.log("Division: ", a / b);

Output

> Addition: 15

> Subtraction: 5

> Multiplication: 50

> Division: 2

Assignment Operators

Assignment operators assign values to variables. The = operator is the simplest assignment operator, but others combine assignments with arithmetic operations.

let x = 10;
x += 5; // x = x + 5
x *= 2; // x = x * 2
console.log(x);

Output

> 30

Comparison Operators

Comparison operators compare two values and return a boolean value: true or false.

console.log(10 > 5);  // true
console.log(10 == "10");  // true
console.log(10 === "10");  // false

Output

> true

> true

> false

Logical Operators

Logical operators are used to combine conditional statements. The common operators are && (AND), || (OR), and ! (NOT).

let a = true;
let b = false;
console.log(a && b); // false
console.log(a || b); // true
console.log(!a); // false

Output

> false

> true

> false

DOM-Based Example

Below is a DOM-based example showcasing the use of JavaScript operators to perform calculations and display the result dynamically in the browser.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS Operators Example</title>
</head>
<body>
    <h1>JavaScript Operators Example</h1>
    <p>Click the button to perform a calculation:</p>
    <button onclick="performCalculation()">Calculate</button>
    <p id="result"></p>

    <script>
        function performCalculation() {
            let a = 10;
            let b = 5;
            let sum = a + b;
            document.getElementById("result").textContent = "The sum is: " + sum;
        }
    </script>
</body>
</html>

Key Takeaways

  • Arithmetic Operators: Perform basic math operations.
  • Assignment Operators: Assign values with or without performing operations.
  • Comparison Operators: Compare values and return boolean results.
  • Logical Operators: Combine or negate conditional statements.
  • DOM-Based Usage: Use operators to dynamically update content in the browser.