๐ŸŒŸ Object-Oriented Programming (OOP) in JavaScript

Definition: OOP is a programming paradigm where we organize code using objects โ€” bundles of data (properties) and behavior (methods).

Benefits in JavaScript:

1. Constructor Functions

Definition: Special function used with new keyword to create objects.

Syntax:

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.sayHello = function() {
    console.log(`Hi, I'm ${this.name}`);
  };
}

const p1 = new Person("Alice", 25);
p1.sayHello();
Reference Image

2. Prototypes & Inheritance

Definition: Objects created from a constructor inherit methods from its prototype.

Syntax:

function Person(name) {
  this.name = name;
}

Person.prototype.greet = function() {
  console.log(`Hello, I'm ${this.name}`);
};

const p1 = new Person("Alice");
p1.greet();
Reference Image

3. class & extends

Definition: ES6 class syntax is a cleaner way to write constructor functions & prototypes. extends allows inheritance.

Syntax:

class Person {
  constructor(name) { this.name = name; }
  greet() { console.log(`Hi, I'm ${this.name}`); }
}

class Student extends Person {
  constructor(name, grade) {
    super(name);
    this.grade = grade;
  }
  study() { console.log(`${this.name} is studying in grade ${this.grade}`); }
}

const s1 = new Student("Bob", 10);
s1.greet();
s1.study();
Reference Image

4. this Keyword

Definition: Refers to the current object executing the function. Context matters.

Syntax:

const obj = {
  name: "Alice",
  greet() { console.log(this.name); }
};
obj.greet();
Reference Image

5. Error Handling

a) try...catch

Definition: Catch runtime errors to prevent crashes.

Syntax:

try {
  let result = unknownVariable + 1;
} catch (error) {
  console.log("Error caught:", error.message);
}

b) throw

Definition: Create custom errors when needed.

Syntax:

function divide(a, b) {
  if (b === 0) { throw new Error("Cannot divide by zero!"); }
  return a / b;
}

try {
  divide(10, 0);
} catch (e) {
  console.log(e.message);
}
Reference Image