Operators

1. Welcome and Icebreaker:

  • Hello coders! What’s an operator you find particularly useful or interesting in any programming language you’ve used?

2. Outline the Session:

  • Today, we’ll cover common operators in TypeScript: Arithmetic, Logical, Comparison, and Bitwise.
  • We’ll see how they work with examples.
  • Learning Outcomes: You’ll be able to use various operators to perform calculations, make decisions, and manipulate data.
  • Let’s dive in!

3. Concept Explanation:

  • Operators are special symbols or keywords that perform operations on one or more values (operands).

  • 1. Arithmetic Operators: Used for mathematical calculations.

    • + (Addition)
    • - (Subtraction)
    • * (Multiplication)
    • / (Division)
    • % (Modulus - remainder of a division)
    • ++ (Increment - increases a value by 1)
    • -- (Decrement - decreases a value by 1)
    • ** (Exponentiation - ES2016, raises to the power of)
  • 2. Comparison Operators: Used to compare two values; they return a boolean (true or false).

    • == (Equal to - performs type coercion, avoid if possible)
    • === (Strictly equal to - compares value and type, preferred)
    • != (Not equal to - performs type coercion)
    • !== (Strictly not equal to - compares value and type, preferred)
    • > (Greater than)
    • < (Less than)
    • >= (Greater than or equal to)
    • <= (Less than or equal to)
  • 3. Logical Operators: Used to combine or invert boolean values.

    • && (Logical AND - true if both operands are true)
    • || (Logical OR - true if at least one operand is true)
    • ! (Logical NOT - inverts the boolean value)
    • Short-circuiting: Logical AND and OR operators exhibit short-circuiting behavior. For expr1 && expr2, if expr1 is false, expr2 is not evaluated. For expr1 || expr2, if expr1 is true, expr2 is not evaluated.
  • 4. Assignment Operators: Used to assign values to variables.

    • = (Assignment)
    • += (Addition assignment, e.g., x += y is x = x + y)
    • -= (Subtraction assignment)
    • *= (Multiplication assignment)
    • /= (Division assignment)
    • %= (Modulus assignment)
    • **= (Exponentiation assignment)
  • 5. Bitwise Operators: Perform operations on the binary representation of numbers. Less common in typical web development but useful in specific scenarios (e.g., graphics, low-level programming, flags).

    • & (Bitwise AND)
    • | (Bitwise OR)
    • ^ (Bitwise XOR)
    • ~ (Bitwise NOT - inverts all bits)
    • << (Left shift - shifts bits to the left, fills with zeros)
    • >> (Sign-propagating right shift - shifts bits to the right, preserves sign)
    • >>> (Zero-fill right shift - shifts bits to the right, fills with zeros)
  • 6. Other Operators:

    • Ternary Operator (Conditional Operator): condition ? exprIfTrue : exprIfFalse - a shorthand for an if-else statement.
    • typeof Operator: Returns a string indicating the type of an unevaluated operand.
    • instanceof Operator: Checks if an object is an instance of a particular class or constructor.
    • Comma Operator: expr1, expr2 - evaluates both operands and returns the value of the last operand. Rarely used.

4. Live Coding Demonstration:

console.log("--- Arithmetic Operators ---");
let num1: number = 10;
let num2: number = 5;
console.log(`num1 (${num1}) + num2 (${num2}) = ${num1 + num2}`); // 15
console.log(`num1 (${num1}) - num2 (${num2}) = ${num1 - num2}`); // 5
console.log(`num1 (${num1}) * num2 (${num2}) = ${num1 * num2}`); // 50
console.log(`num1 (${num1}) / num2 (${num2}) = ${num1 / num2}`); // 2
console.log(`10 % 3 = ${10 % 3}`); // 1
console.log(`2 ** 4 = ${2 ** 4}`); // 16

let counter: number = 0;
counter++;
console.log("Counter after ++:", counter); // 1
counter--;
console.log("Counter after --:", counter); // 0

console.log("\n--- Comparison Operators ---");
let valA: number = 5;
let valB: string = "5";
console.log(`valA (${valA}) == valB ("${valB}"): ${valA == (valB as any)}`); // true (loose equality, type coercion)
console.log(`valA (${valA}) === valB ("${valB}"): ${valA === (valB as any)}`); // false (strict equality, different types)
console.log(`valA (${valA}) != valB ("${valB}"): ${valA != (valB as any)}`); // false
console.log(`valA (${valA}) !== valB ("${valB}"): ${valA !== (valB as any)}`); // true
console.log(`10 > 5: ${10 > 5}`); // true
console.log(`10 < 5: ${10 < 5}`); // false
console.log(`10 >= 10: ${10 >= 10}`); // true
console.log(`10 <= 5: ${10 <= 5}`); // false

console.log("\n--- Logical Operators ---");
let isAdult: boolean = true;
let hasLicense: boolean = false;
console.log(`isAdult && hasLicense: ${isAdult && hasLicense}`); // false
console.log(`isAdult || hasLicense: ${isAdult || hasLicense}`); // true
console.log(`!isAdult: ${!isAdult}`); // false

// Short-circuiting
console.log("Short-circuiting AND:");
let x = 0;
(false && ++x); // ++x is not evaluated
console.log("x after (false && ++x):", x); // 0

console.log("Short-circuiting OR:");
let y = 0;
(true || ++y); // ++y is not evaluated
console.log("y after (true || ++y):", y); // 0

console.log("\n--- Assignment Operators ---");
let score: number = 100;
score += 10; // score = score + 10;
console.log("Score after += 10:", score); // 110
score -= 20;
console.log("Score after -= 20:", score); // 90
score *= 2;
console.log("Score after *= 2:", score); // 180
score /= 3;
console.log("Score after /= 3:", score); // 60

console.log("\n--- Bitwise Operators (Example) ---");
// Often used for flags or direct hardware manipulation.
// 5 (binary 0101)
// 3 (binary 0011)
console.log(`5 & 3 = ${5 & 3}`);   // 0001 (decimal 1)
console.log(`5 | 3 = ${5 | 3}`);   // 0111 (decimal 7)
console.log(`5 ^ 3 = ${5 ^ 3}`);   // 0110 (decimal 6)
console.log(`~5 = ${~5}`);      // Inverts all bits. Result depends on integer size and representation.
                         // For 32-bit signed int: -(5+1) = -6
console.log(`5 << 1 = ${5 << 1}`); // 1010 (decimal 10)
console.log(`5 >> 1 = ${5 >> 1}`); // 0010 (decimal 2) (sign-propagating)
console.log(`-5 >> 1 = ${-5 >> 1}`); // FFFFFFFD (decimal -3) (sign-propagating)
console.log(`5 >>> 1 = ${5 >>> 1}`); // 0010 (decimal 2) (zero-fill)
console.log(`-5 >>> 1 = ${-5 >>> 1}`); // Large positive number (zero-fill)

console.log("\n--- Ternary Operator ---");
let age: number = 18;
let beverage: string = (age >= 21) ? "Beer" : "Juice";
console.log(`Beverage for age ${age}: ${beverage}`); // Juice (if age is 18)

console.log("\n--- typeof Operator ---");
console.log(`typeof 42: ${typeof 42}`); // "number"
console.log(`typeof "hello": ${typeof "hello"}`); // "string"
console.log(`typeof true: ${typeof true}`); // "boolean"
console.log(`typeof {}: ${typeof {}}`); // "object"
console.log(`typeof []: ${typeof []}`); // "object" (arrays are objects)
console.log(`typeof undefined: ${typeof undefined}`); // "undefined"
console.log(`typeof null: ${typeof null}`); // "object" (a known quirk in JavaScript)
console.log(`typeof function(){}: ${typeof function(){}}`); // "function"

5. Tasks:

  • Short Exercise:
    1. Arithmetic: Declare two number variables, perform multiplication and modulus operations, and print the results.
    2. Comparison: Declare a variable myAge and set it to your age. Use comparison operators to check if myAge is greater than or equal to 18 and print the boolean result.
    3. Logical: Declare two boolean variables, isLoggedIn and isAdmin. Write an expression that is true if the user is logged in AND is an admin. Print the result. Write another expression that is true if the user is logged in OR is an admin.
    4. Assignment: Declare a variable points initialized to 50. Use += to add 10 points and then -= to subtract 5 points. Print the final points.
    5. Ternary: Write a ternary operator that assigns “Pass” to a variable gradeStatus if a score variable (e.g., 75) is greater than or equal to 70, and “Fail” otherwise. Print gradeStatus.