≡ Menu

Object-Oriented Programming (OOP) is a programming paradigm that uses objects—data structures consisting of data fields and methods—to design applications and computer programs.

JavaScript is a multi-paradigm language that supports OOP principles, making it a powerful tool for building complex, scalable applications.

This tutorial will guide you through the core concepts of OOP in modern JavaScript, primarily using ES6 Classes.


1. 🧱 Objects and Classes

The fundamental concept of OOP is the Class, which acts as a blueprint for creating Objects.

A. Objects

An object is an instance of a class, representing a real-world entity. In JavaScript, you can create objects using literal notation, constructor functions, or classes.

// Object Literal Notation
const car = {
  make: "Honda",
  model: "Civic",
  year: 2020,
  start: function() {
    console.log("Engine started!");
  }
};

console.log(car.make); // Output: Honda
car.start();          // Output: Engine started!

B. Classes (The Blueprint)

ES6 introduced the class keyword, which provides a much cleaner and more familiar syntax for creating blueprints.

// 
class Vehicle{
  // 1. The constructor method is called when a new object is created.
  constructor(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
  }

  // 2. A method (function) that all Vehicle objects will have
  getDetails() {
    return `${this.year} ${this.make} ${this.model}`;
  }
}

// Creating a new object (instantiation)
const myCar = new Vehicle("Toyota", "Camry", 2022);

console.log(myCar.getDetails()); // Output: 2022 Toyota Camry

2. 🔑 The Four Pillars of OOP

OOP is built upon four main principles: Encapsulation, Abstraction, Inheritance, and Polymorphism.

A. Encapsulation (Bundling Data and Methods)

Encapsulation means bundling the data (properties) and the methods (functions) that operate on that data into a single unit (the object/class). It also involves restricting direct access to some of an object’s components, which is crucial for preventing accidental modification.

  • In JavaScript: Traditionally, JavaScript has not had true private properties. Developers use conventions, like prefixing a property with an underscore (_), to signal that it should be treated as private.

  • Modern JavaScript (ES2020+): You can now define truly private class fields using the # prefix.

class BankAccount{
  #balance = 0; // Truly private field

  constructor(initialDeposit) {
    if (initialDeposit > 0) {
      this.#balance = initialDeposit;
    }
  }

  deposit(amount) {
    if (amount > 0) {
      this.#balance += amount;
    }
  }

  // A method (public interface) to safely retrieve the private data
  getBalance() {
    return this.#balance;
  }
}

const account = new BankAccount(100);
account.deposit(50);
console.log(account.getBalance()); // Output: 150
// console.log(account.#balance); // SyntaxError: Private field '#balance' must be declared in an enclosing class

B. Inheritance (The “is-a” Relationship)

Inheritance allows a new class (the subclass or child class) to inherit properties and methods from an existing class (the superclass or parent class). This promotes code reusability.

  • extends: Used to establish the inheritance relationship.

  • super(): Used inside the subclass’s constructor to call the parent class’s constructor and initialize its properties.

// 
class Car extends Vehicle{ // Car is a subclass of Vehicle
  constructor(make, model, year, doorCount) {
    // Call the parent (Vehicle) constructor
    super(make, model, year); 
    this.doorCount = doorCount;
  }

  // A method specific to Car
  getDoorCount() {
    return `This car has ${this.doorCount} doors.`;
  }
}

const sedan = new Car("Ford", "Focus", 2018, 4);

console.log(sedan.getDetails());     // Inherited from Vehicle: 2018 Ford Focus
console.log(sedan.getDoorCount());   // Own method: This car has 4 doors.

C. Polymorphism (Many Forms)

Polymorphism allows objects to take on “many forms,” meaning a single interface (a method name) can be used to represent different implementations. The most common form in JavaScript OOP is Method Overriding.

  • Method Overriding: A subclass provides its own specific implementation of a method that is already defined in its superclass.

class ElectricCar extends Car{
  constructor(make, model, year, doorCount, range) {
    super(make, model, year, doorCount);
    this.range = range;
  }

  // Method Overriding: Overrides the getDetails() method from Vehicle/Car
  getDetails() {
    // We can call the parent's method using super
    const carDetails = super.getDetails(); 
    return `${carDetails} and has a ${this.range} mile range.`;
  }
}

const tesla = new ElectricCar("Tesla", "Model 3", 2024, 4, 333);

// The getDetails() method is called, but the specific implementation 
// from ElectricCar is executed.
console.log(tesla.getDetails()); 
// Output: 2024 Tesla Model 3 and has a 333 mile range.

D. Abstraction (Hiding Complexity)

Abstraction is the concept of showing only essential information and hiding complex implementation details.

In JavaScript:

  • Classes/Objects achieve abstraction by providing public methods (like getBalance() or getDetails()) that serve as a simple, high-level interface, while the internal logic (like how #balance is updated) remains hidden.

  • By using methods to interact with data (Encapsulation), you naturally implement Abstraction.


3. 📝 Summary of OOP Terms

Term Definition JavaScript Example
Class A blueprint for creating objects. class Vehicle { ... }
Object An instance of a class. const myCar = new Vehicle(...)
Property A piece of data (variable) associated with an object. this.make
Method A function associated with an object. getDetails()
Constructor A special method for creating and initializing an object created with a class. constructor(...)

Useful links below:

Let me & my team build you a money making website/blog for your business https://bit.ly/tnrwebsite_service

Get Bluehost hosting for as little as $1.99/month (save 75%)…https://bit.ly/3C1fZd2

Best email marketing automation solution on the market! http://www.aweber.com/?373860

Build high converting sales funnels with a few simple clicks of your mouse! https://bit.ly/484YV29

Join my Patreon for one-on-one coaching and help with your coding…https://www.patreon.com/c/TyronneRatcliff

Buy me a coffee ☕️https://buymeacoffee.com/tyronneratcliff

{ 0 comments }

Loops are a fundamental concept in programming, allowing you to execute a block of code repeatedly.

Instead of writing the same code over and over, loops help you automate repetitive tasks efficiently.

In JavaScript, there are several types of loops, each suited for different situations.

1. The for Loop: The Go-To Repeater

The for loop is the most common and generally the most structured loop.

It’s perfect when you know exactly how many times you want the loop to run (e.g., iterating through an array or counting to a specific number).

Structure

The for loop has three main expressions inside its parentheses, separated by semicolons:

  1. Initialization: Executed once before the loop starts. This usually initializes a counter variable (e.g., i=0).

  2. Condition: Evaluated before each loop iteration. If it’s true, the loop continues; if false, the loop stops.

  3. Increment/Decrement: Executed after each loop iteration. This usually updates the counter variable (e.g., i++).

Example

Let’s print the numbers from 1 to 5:

for (let i = 1; i <= 5; i++) {
  console.log("Count: " + i);
}
/*
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
*/

2. The while Loop: Condition-Based Running

The while loop runs as long as a specified condition remains true. It’s ideal when you don’t know the exact number of iterations beforehand, but you know the condition that must be met to stop the loop.

Structure

The while loop only requires a condition inside its parentheses. Crucially, you must manage the variable that controls the condition inside the loop’s body to prevent an infinite loop.

Example

Let’s do the same counting exercise with a while loop:

let count = 1;

while (count <= 5) {
  console.log("Count: " + count);
  count++; // Don't forget to update the counter!
}
/*
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
*/

3. The do...while Loop: Guaranteed Execution

The do...while loop is very similar to the while loop, but with one key difference: the code block is executed at least once before the condition is checked.

Structure

The do block executes, and then the while condition is checked.

Example

Even if the condition is initially false, the do block runs once:

let j = 10;

do {
  console.log("This will print once: " + j);
  j++;
} while (j < 5); // The condition is false (10 < 5 is false)
/*
Output:
This will print once: 10
*/

4. Loops for Iterating Collections (Arrays)

JavaScript provides specialized loops for easily working with arrays and other iterable objects.

A. for...of: Iterating Over Values

The for...of loop iterates over the values (elements) of an iterable object (like an array, string, or map).

const fruits = ["apple", "banana", "cherry"];

for (const fruit of fruits) {
  console.log("I like " + fruit);
}
/*
Output:
I like apple
I like banana
I like cherry
*/

B. for...in: Iterating Over Object Properties (Keys)

The for...in loop iterates over the enumerable properties (keys/indexes) of an object. While it can be used for arrays, it’s generally discouraged in favor of for, for...of, or Array.prototype.forEach().

const user = { name: "Alice", age: 30, city: "NY" };

for (const key in user) {
  console.log(key + ": " + user[key]);
}
/*
Output:
name: Alice
age: 30
city: NY
*/

🛑 Loop Control Statements

Sometimes you need to jump out of a loop or skip an iteration. That’s where control statements come in.

  • break: Immediately exits the entire loop. Execution continues with the code following the loop.

  • continue: Skips the rest of the current iteration and jumps to the next iteration of the loop.

Example:

for (let i = 1; i <= 5; i++) {
  if (i === 3) {
    continue; // Skip the number 3
  }
  if (i === 5) {
    break; // Stop completely when we hit 5
  }
  console.log(i);
}
/*
Output:
1
2
4
*/

Loops are the backbone of automated tasks in JavaScript.

Understanding when to use a for, while, or for...of loop is key to writing clean, efficient, and powerful code!

Useful links below:

Let me & my team build you a money making website/blog for your business https://bit.ly/tnrwebsite_service

Get Bluehost hosting for as little as $1.99/month (save 75%)…https://bit.ly/3C1fZd2

Best email marketing automation solution on the market! http://www.aweber.com/?373860

Build high converting sales funnels with a few simple clicks of your mouse! https://bit.ly/484YV29

Join my Patreon for one-on-one coaching and help with your coding…https://www.patreon.com/c/TyronneRatcliff

Buy me a coffee ☕️https://buymeacoffee.com/tyronneratcliff

{ 0 comments }