Skillversitas

Operators in JavaScript

What Is an Operator?

An operator is a symbol used to perform an operation on values (operands). JavaScript has several categories of operators.

1. Arithmetic Operators

Used for basic mathematical operations.

// Basic arithmetic operators
let a = 10;
let b = 3;

console.log(a + b);   // 13  (addition)
console.log(a - b);   // 7   (subtraction)
console.log(a * b);   // 30  (multiplication)
console.log(a / b);   // 3.333... (division)
console.log(a % b);   // 1   (modulus/remainder)
console.log(a ** b);  // 1000 (exponentiation)

// Example in an academic portal
let totalCredits = 3 + 3 + 4 + 3;        // 13 credits
let average = (85 + 90 + 78 + 92) / 4; // 86.25
let remainder = 13 % 4;                // 1 (13 divided by 4 leaves a remainder of 1)

Increment and Decrement

// Increment (++): adds 1
let counter = 0;
counter++;     // counter = 1
counter++;     // counter = 2
console.log(counter); // 2

// Pre-increment vs post-increment
let x = 5;
console.log(x++); // 5 (post-increment: display first, then add)
console.log(x);   // 6

let y = 5;
console.log(++y); // 6 (pre-increment: add first, then display)
console.log(y);   // 6

// Decrement (--): subtracts 1
let semester = 8;
semester--;     // semester = 7
console.log(semester); // 7

2. Assignment Operators

Used to assign a value to a variable.

// Basic assignment
let score = 85;      // =

// Compound assignment
let total = 100;
total += 20;    // total = total + 20 = 120
total -= 10;    // total = total - 10 = 110
total *= 2;     // total = total * 2 = 220
total /= 4;     // total = total / 4 = 55
total %= 7;     // total = total % 7 = 6
total **= 2;    // total = total ** 2 = 36

console.log(total); // 36

// Usage in an academic portal
let creditsTaken = 0;
creditsTaken += 3;  // Take the Web Programming course
creditsTaken += 3;  // Take the Database course
creditsTaken += 4;  // Take the Algorithms course
console.log(`Total credits taken: ${creditsTaken}`); // 10

3. Comparison Operators

Used to compare two values.

Equal and Not Equal (Type Coercion)

// == (loose equality): compares VALUE with type coercion
console.log(5 == "5");     // true (string is converted to number)
console.log(0 == false);   // true (false is converted to 0)
console.log(null == undefined); // true
console.log("" == 0);      // true

// === (strict equality): compares VALUE and TYPE
console.log(5 === "5");    // false (number !== string)
console.log(0 === false);  // false (number !== boolean)
console.log(null === undefined); // false
console.log("" === 0);     // false

// != (loose not equal)
console.log(5 != "5");     // false

// !== (strict not equal) — ALWAYS USE THIS ONE
console.log(5 !== "5");    // true

Relational Operators

// Relational comparisons
let gpa = 3.75;

console.log(gpa > 3.5);    // true (greater than)
console.log(gpa >= 3.5);   // true (greater than or equal)
console.log(gpa < 4.0);    // true (less than)
console.log(gpa <= 3.0);   // false (less than or equal)

// Example: determining a classification based on GPA
function determineClassification(gpa) {
    if (gpa >= 3.5) return "Cum Laude";
    if (gpa >= 3.0) return "Very Satisfactory";
    if (gpa >= 2.5) return "Satisfactory";
    if (gpa >= 2.0) return "Fair";
    return "Poor";
}

console.log(determineClassification(3.75)); // "Cum Laude"
console.log(determineClassification(2.25)); // "Fair"

4. Logical Operators

Used to combine boolean conditions.

// AND (&&): TRUE if ALL are true
console.log(true && true);    // true
console.log(true && false);   // false
console.log(false && false);  // false

// OR (||): TRUE if AT LEAST one is true
console.log(true || true);    // true
console.log(true || false);   // true
console.log(false || false);  // false

// NOT (!): inverts a boolean
console.log(!true);   // false
console.log(!false);  // true
console.log(!0);      // true
console.log(!"");     // true
console.log(!"John"); // false

// Example in an academic portal
let gpa = 3.75;
let paymentStatus = true;
let hasRegistered = true;

// Check exam eligibility
if (gpa >= 2.0 && paymentStatus && hasRegistered) {
    console.log("You are eligible to take the exam.");
} else {
    console.log("You do not meet the requirements yet.");
}

// Check scholarship eligibility
if (gpa >= 3.5 || (gpa >= 3.0 && paymentStatus)) {
    console.log("You have the potential to receive a scholarship.");
}

Short-Circuit Evaluation

// AND (&&): stops at the first FALSY value
// OR (||): stops at the first TRUTHY value

// AND — returns the last value checked if all are truthy
let name = "John" && "Mike" && "Alice";
console.log(name); // "Alice" (all truthy, returns the last one)

let empty = "" && "John";
console.log(empty); // "" (stops at "")

// OR — returns the first truthy value
let default1 = "" || "Default";
console.log(default1); // "Default" (stops at a truthy value)

let exist = "John" || "Default";
console.log(exist); // "John" (stops at a truthy value)

// Usage: default values in an academic portal
function showProfile(student) {
    const name = student?.name || "Unknown";
    const major = student?.major || "To be determined";
    const photo = student?.photo || "/assets/default-avatar.png";

    return { name, major, photo };
}

// Optional chaining + short-circuit
const profile1 = showProfile({ name: "John", major: "CS" });
const profile2 = showProfile({});
console.log(profile1); // { name: "John", major: "CS", photo: "..." }
console.log(profile2); // { name: "Unknown", major: "To be determined", photo: "..." }

5. The Ternary Operator

A shorthand for if...else.

// Syntax: condition ? valueIfTrue : valueIfFalse

let gpa = 3.75;
let classification = gpa >= 3.5 ? "Cum Laude" : "Not Cum Laude";
console.log(classification); // "Cum Laude"

// Nested ternary (avoid it if it gets too complex)
let score = 85;
let grade = score >= 90 ? "A" :
            score >= 80 ? "B" :
            score >= 70 ? "C" :
            score >= 60 ? "D" : "E";
console.log(grade); // "B"

// Example in a template literal
const status = true;
console.log(`Status: ${status ? "Active ✅" : "Inactive ❌"}`);

// Usage inside a function
function checkScholarshipEligibility(gpa, parentIncome) {
    return (gpa >= 3.5 && parentIncome < 5000000)
        ? "Eligible to receive a scholarship"
        : "Not eligible";
}

6. Bitwise Operators

Used for operations at the bit level (rarely used in web development).

// Bitwise operators
let a = 5;    // 101 in binary
let b = 3;    // 011 in binary

console.log(a & b);   // 1 (AND: 101 & 011 = 001)
console.log(a | b);   // 7 (OR: 101 | 011 = 111)
console.log(a ^ b);   // 6 (XOR: 101 ^ 011 = 110)
console.log(~a);      // -6 (NOT: bitwise inverse)
console.log(a << 1);  // 10 (left shift)
console.log(a >> 1);  // 2 (right shift)

7. The Nullish Coalescing Operator (??)

Returns the right-hand value only if the left-hand value is null or undefined.

// ?? vs ||
let input1 = 0;
let input2 = "";
let input3 = null;
let input4 = undefined;

// OR: stops at any falsy (including 0 and "")
console.log(input1 || "default"); // "default" (0 is falsy!)
console.log(input2 || "default"); // "default" ("" is falsy!)

// Nullish coalescing: stops at null/undefined ONLY
console.log(input1 ?? "default"); // 0 (0 is not null/undefined!)
console.log(input2 ?? "default"); // "" ("" is not null/undefined!)
console.log(input3 ?? "default"); // "default"
console.log(input4 ?? "default"); // "default"

// Usage in an academic portal
function getSchedule(classInfo) {
    return {
        time: classInfo.time ?? "08:00",
        room: classInfo.room ?? "To be determined",
        instructor: classInfo.instructor ?? "TBD"
    };
}

const schedule1 = getSchedule({ time: "10:00", room: "Lab 3" });
const schedule2 = getSchedule({});
console.log(schedule1); // { time: "10:00", room: "Lab 3", instructor: "TBD" }
console.log(schedule2); // { time: "08:00", room: "To be determined", instructor: "TBD" }

Case Study: Calculating GPA and Validating Input

// === GPA CALCULATION SYSTEM ===

const gradeList = [
    { course: "Web Programming",  score: 85, credits: 3 },
    { course: "Database",         score: 78, credits: 3 },
    { course: "Algorithms",       score: 92, credits: 4 },
    { course: "Computer Networks",score: 88, credits: 3 },
    { course: "English",          score: 75, credits: 2 }
];

function calcGPA(gradeList) {
    // Calculate the total weight and total credits
    let totalWeight = 0;
    let totalCredits = 0;

    for (const item of gradeList) {
        let weight;

        // Convert the score to a grade point (4.0 scale)
        if (item.score >= 85)      weight = 4.0;
        else if (item.score >= 80) weight = 3.5;
        else if (item.score >= 75) weight = 3.0;
        else if (item.score >= 70) weight = 2.5;
        else if (item.score >= 65) weight = 2.0;
        else if (item.score >= 50) weight = 1.0;
        else                       weight = 0;

        // Accumulate
        totalWeight += weight * item.credits;
        totalCredits += item.credits;
    }

    // Calculate the GPA
    const gpa = totalCredits > 0 ? totalWeight / totalCredits : 0;

    return {
        gpa: Math.round(gpa * 100) / 100,
        totalCredits: totalCredits,
        averageScore: gradeList.reduce((sum, item) => sum + item.score, 0) / gradeList.length
    };
}

// === INPUT VALIDATION ===

function validateInput(form) {
    const errors = [];

    // Validate student ID: must be 10 digits
    const studentIdValid = form.studentId?.length === 10 && /^\d{10}$/.test(form.studentId);
    if (!studentIdValid) errors.push("Student ID must be 10 digits!");

    // Validate name: must be a string, at least 3 characters
    const nameValid = typeof form.name === "string" && form.name.length >= 3;
    if (!nameValid) errors.push("Name must be at least 3 characters!");

    // Validate credits: must be a number, between 1 and 24
    const creditsValid = typeof form.credits === "number" && form.credits >= 1 && form.credits <= 24;
    if (!creditsValid) errors.push("Credits must be between 1 and 24!");

    // Validate email: must contain @
    const emailValid = typeof form.email === "string" && form.email.includes("@");
    if (!emailValid) errors.push("Email is not valid!");

    // Validate semester: must be a number, between 1 and 14
    const semesterValid = typeof form.semester === "number" && form.semester >= 1 && form.semester <= 14;
    if (!semesterValid) errors.push("Semester must be between 1 and 14!");

    return {
        valid: errors.length === 0,
        errors: errors
    };
}

// === USAGE ===

const gpaResult = calcGPA(gradeList);
console.log("=== GPA CALCULATION RESULT ===");
console.log(`GPA: ${gpaResult.gpa}`);
console.log(`Total credits: ${gpaResult.totalCredits}`);
console.log(`Average Score: ${Math.round(gpaResult.averageScore)}`);

const classification = gpaResult.gpa >= 3.5 ? "Cum Laude" :
                       gpaResult.gpa >= 3.0 ? "Very Satisfactory" :
                       gpaResult.gpa >= 2.5 ? "Satisfactory" :
                       gpaResult.gpa >= 2.0 ? "Fair" : "Poor";
console.log(`Classification: ${classification}`);

// Short-circuit for defaults
const instructorName = null;
const defaultName = instructorName ?? "Instructor To Be Determined";
console.log(`Instructor: ${defaultName}`);

Summary

Category Operator Example
Arithmetic +, -, *, /, %, ** 5 + 3
Assignment =, +=, -=, *=, /= x += 10
Comparison ==, ===, !=, !==, >, <, >=, <= a === b
Logical &&, \|\|, !, ?? a && b
Ternary ? : x > 0 ? "pos" : "neg"
Bitwise &, \|, ^, ~, <<, >> a & b

Use === (strict equality) instead of == (loose equality) to avoid unexpected bugs caused by type coercion.