JavaScript and TypeScript course Β· Module 2: Functions, Arrays and Objects

Creating Objects (Literals, Constructors)

11 min read Β·
In this lesson8

In Jurassic Park we use JavaScript objects to represent many elements of our ecosystem - from dinosaurs and their behavior, through the areas of the park, to staff data and safety procedures. Objects are a fundamental data type in JavaScript that lets us build complex data structures with properties and methods.

Object Literals

The simplest way to create objects in JavaScript is to use an object literal - the curly brace notation {}.

// A simple dinosaur object created with an object literal
const velociraptor = {
  name: "Blue",
  species: "Velociraptor",
  age: 4,
  length: 2.1, // meters
  weight: 80, // kilograms
  maxSpeed: 64, // km/h
  diet: "carnivore",
  location: "Sector B",
  dangerous: true
};

console.log(velociraptor.name); // "Blue"
console.log(velociraptor.species); // "Velociraptor"
console.log(velociraptor.maxSpeed); // 64

Accessing Properties

We can access an object's properties in two ways:

// Dot notation
console.log(velociraptor.diet); // "carnivore"

// Bracket notation (useful when the property name is stored in a variable)
const propertyName = "location";
console.log(velociraptor[propertyName]); // "Sector B"

// Bracket notation is also useful when the property name contains special characters or spaces
const dinoDetails = {
  "full name": "Velociraptor antirrhopus",
  "security-level": "Alpha"
};

console.log(dinoDetails["full name"]); // "Velociraptor antirrhopus"
console.log(dinoDetails["security-level"]); // "Alpha"

Object Methods

Objects can also contain functions, which we call methods:

const velociraptor = {
  name: "Blue",
  species: "Velociraptor",
  age: 4,
  hunger: 50, // percent (0-100)
  health: 100, // percent (0-100)

  // Method for feeding the dinosaur
  feed: function() {
    if (this.hunger <= 0) {
      return "Blue is not hungry.";
    }

    this.hunger -= 30;
    if (this.hunger < 0) this.hunger = 0;

    return "Blue has been fed. Hunger level: " + this.hunger + "%";
  },

  // Shorter method syntax (introduced in ES6)
  makeSound() {
    return "Blue makes a sharp, piercing sound!";
  },

  // Method that checks the health status
  checkStatus() {
    return `Dinosaur: ${this.name} (Species: ${this.species})
Health status: ${this.health}%
Hunger level: ${this.hunger}%
Overall condition: ${this.health > 80 ? "Excellent" : this.health > 50 ? "Good" : "Needs veterinary care"}`;
  }
};

console.log(velociraptor.makeSound()); // "Blue makes a sharp, piercing sound!"
console.log(velociraptor.feed()); // "Blue has been fed. Hunger level: 20%"
console.log(velociraptor.checkStatus());

The this keyword in methods refers to the object on which the method is called.

Adding and Removing Properties Dynamically

We can dynamically add and remove properties of JavaScript objects:

const triceratops = {
  name: "Trixie",
  species: "Triceratops",
  age: 6
};

// Adding new properties
triceratops.health = 95;
triceratops["location"] = "Sector C";

// Adding a method
triceratops.updateHealth = function(amount) {
  this.health += amount;
  if (this.health > 100) this.health = 100;
  if (this.health < 0) this.health = 0;
  return `${this.name}'s health updated to ${this.health}%`;
};

console.log(triceratops.updateHealth(-15)); // "Trixie's health updated to 80%"

// Removing a property
delete triceratops.age;
console.log(triceratops.age); // undefined

Constructors and the new Operator

When we need to create many similar objects, a more efficient approach is to use a constructor function and the new operator.

// Constructor function for dinosaurs
function Dinosaur(name, species, age, diet) {
  this.name = name;
  this.species = species;
  this.age = age;
  this.diet = diet;
  this.health = 100;
  this.hunger = 50;

  // Method shared by all dinosaurs
  this.feed = function() {
    this.hunger -= 30;
    if (this.hunger < 0) this.hunger = 0;
    return `${this.name} has been fed. Hunger level: ${this.hunger}%`;
  };
}

// Creating new dinosaur instances
const blue = new Dinosaur("Blue", "Velociraptor", 4, "carnivore");
const trixie = new Dinosaur("Trixie", "Triceratops", 6, "herbivore");
const rex = new Dinosaur("Rex", "Tyrannosaurus", 8, "carnivore");

console.log(blue.species); // "Velociraptor"
console.log(trixie.diet); // "herbivore"
console.log(rex.feed()); // "Rex has been fed. Hunger level: 20%"

The constructor function creates a "template" for objects, and the new operator creates a new object instance based on that template.

Advantages of Constructors:

  1. Consistency - all objects have the same set of properties and methods
  2. Scalability - it is easier to create many similar objects
  3. Readability - the code becomes more predictable and easier to maintain

Checking an Object's Type - the instanceof Operator

We can check whether an object was created with a particular constructor:

console.log(blue instanceof Dinosaur); // true
console.log(velociraptor instanceof Dinosaur); // false (it was created as a literal)

Classes (ES6+)

Newer versions of JavaScript (ES6+) introduced classes, which provide a friendlier syntax for object-oriented programming. Under the hood they are still constructor functions, just with a more readable syntax.

class Dinosaur {
  constructor(name, species, age, diet) {
    this.name = name;
    this.species = species;
    this.age = age;
    this.diet = diet;
    this.health = 100;
    this.hunger = 50;
    this.isAsleep = false;
  }

  // Methods are automatically added to the prototype
  feed() {
    if (this.isAsleep) {
      return `${this.name} is asleep. Better not to wake him/her for feeding.`;
    }

    this.hunger -= 30;
    if (this.hunger < 0) this.hunger = 0;
    return `${this.name} has been fed. Hunger level: ${this.hunger}%`;
  }

  sleep() {
    this.isAsleep = true;
    return `${this.name} falls asleep.`;
  }

  wakeUp() {
    this.isAsleep = false;
    return `${this.name} wakes up.`;
  }

  getStatus() {
    return `
Dinosaur: ${this.name} (Species: ${this.species})
Age: ${this.age} years
Diet: ${this.diet === "carnivore" ? "Carnivorous" : "Herbivorous"}
Health status: ${this.health}%
Hunger level: ${this.hunger}%
State: ${this.isAsleep ? "Asleep" : "Active"}`;
  }
}

// Creating an instance of the class
const blue = new Dinosaur("Blue", "Velociraptor", 4, "carnivore");
console.log(blue.getStatus());

console.log(blue.sleep()); // "Blue falls asleep."
console.log(blue.feed()); // "Blue is asleep. Better not to wake him/her for feeding."
console.log(blue.wakeUp()); // "Blue wakes up."
console.log(blue.feed()); // "Blue has been fed. Hunger level: 20%"

Inheritance with Classes

Classes make it easy to implement inheritance:

// Base class
class Animal {
  constructor(name, species) {
    this.name = name;
    this.species = species;
    this.alive = true;
  }

  makeSound() {
    return "The animal makes a sound";
  }
}

// Derived class inheriting from Animal
class Dinosaur extends Animal {
  constructor(name, species, diet) {
    // We call the base class constructor
    super(name, species);
    this.diet = diet;
    this.health = 100;
  }

  // We override the method from the base class
  makeSound() {
    if (this.diet === "carnivore") {
      return "ROAR!!! A terrifying roar!";
    } else {
      return "A gentle, low rumble.";
    }
  }

  // We add new methods
  eat(food) {
    if (this.diet === "carnivore" && food.type === "meat") {
      return `${this.name} eats ${food.name} with relish!`;
    } else if (this.diet === "herbivore" && food.type === "plant") {
      return `${this.name} happily nibbles on ${food.name}.`;
    } else {
      return `${this.name} is not interested in eating ${food.name}.`;
    }
  }
}

// Objects representing food
const meat = { name: "meat", type: "meat" };
const plants = { name: "plants", type: "plant" };

// We create dinosaur instances
const rex = new Dinosaur("Rex", "Tyrannosaurus", "carnivore");
const spike = new Dinosaur("Spike", "Stegosaurus", "herbivore");

console.log(rex.makeSound()); // "ROAR!!! A terrifying roar!"
console.log(spike.makeSound()); // "A gentle, low rumble."

console.log(rex.eat(meat)); // "Rex eats meat with relish!"
console.log(rex.eat(plants)); // "Rex is not interested in eating plants."
console.log(spike.eat(plants)); // "Spike happily nibbles on plants."

Static Methods

Static methods are called on the class itself, not on its instances:

class DinosaurDatabase {
  static dinoCount = 0;

  constructor(name, species) {
    this.name = name;
    this.species = species;
    DinosaurDatabase.dinoCount++;
  }

  // Instance method - requires creating an object
  getInfo() {
    return `${this.name} (${this.species})`;
  }

  // Static method - called on the class, not on an instance
  static getTotalDinosaurCount() {
    return `Total number of dinosaurs in the database: ${DinosaurDatabase.dinoCount}`;
  }

  static compareAge(dino1, dino2) {
    if (!dino1.age || !dino2.age) return "No age data available.";

    if (dino1.age > dino2.age) {
      return `${dino1.name} is older than ${dino2.name}.`;
    } else if (dino1.age < dino2.age) {
      return `${dino1.name} is younger than ${dino2.name}.`;
    } else {
      return `${dino1.name} and ${dino2.name} are the same age.`;
    }
  }
}

const dino1 = new DinosaurDatabase("Rex", "Tyrannosaurus");
dino1.age = 8;

const dino2 = new DinosaurDatabase("Blue", "Velociraptor");
dino2.age = 4;

const dino3 = new DinosaurDatabase("Trixie", "Triceratops");
dino3.age = 6;

console.log(DinosaurDatabase.getTotalDinosaurCount()); // "Total number of dinosaurs in the database: 3"
console.log(DinosaurDatabase.compareAge(dino1, dino2)); // "Rex is older than Blue."
console.log(DinosaurDatabase.compareAge(dino2, dino3)); // "Blue is younger than Trixie."

Object.create()

The Object.create() method lets you create new objects with a specified prototype:

// Prototype object for all dinosaurs
const dinoPrototype = {
  makeSound() {
    return "Roar!";
  },
  eat() {
    return `${this.name} is eating.`;
  }
};

// Creating an object with dinoPrototype as its prototype
const rex = Object.create(dinoPrototype);
rex.name = "Rex";
rex.species = "Tyrannosaurus";

console.log(rex.name); // "Rex"
console.log(rex.makeSound()); // "Roar!"
console.log(rex.eat()); // "Rex is eating."

Factory Functions

Factory functions are functions that create and return objects without using new:

// Factory function for creating dinosaur objects
function createDinosaur(name, species, diet) {
  return {
    name,  // Shorthand syntax for name: name in ES6+
    species,
    diet,
    health: 100,
    hunger: 50,

    feed() {
      this.hunger -= 30;
      if (this.hunger < 0) this.hunger = 0;
      return `${this.name} has been fed. Hunger level: ${this.hunger}%`;
    },

    getStatus() {
      return `${this.name} (${this.species}) - Health: ${this.health}%, Hunger: ${this.hunger}%`;
    }
  };
}

const blue = createDinosaur("Blue", "Velociraptor", "carnivore");
const trixie = createDinosaur("Trixie", "Triceratops", "herbivore");

console.log(blue.getStatus()); // "Blue (Velociraptor) - Health: 100%, Hunger: 50%"
console.log(blue.feed()); // "Blue has been fed. Hunger level: 20%"

Objects in Practice in Jurassic Park

Dinosaur Management System

class DinosaurManager {
  constructor() {
    this.dinosaurs = [];
    this.enclosures = [];
  }

  addDinosaur(dino) {
    this.dinosaurs.push(dino);
    console.log(`New dinosaur added: ${dino.name} (${dino.species})`);
  }

  addEnclosure(enclosure) {
    this.enclosures.push(enclosure);
    console.log(`New enclosure added: ${enclosure.name} (Capacity: ${enclosure.capacity})`);
  }

  assignDinosaurToEnclosure(dinoName, enclosureName) {
    const dino = this.dinosaurs.find(d => d.name === dinoName);
    const enclosure = this.enclosures.find(e => e.name === enclosureName);

    if (!dino) {
      return `Error: Dinosaur named ${dinoName} not found.`;
    }

    if (!enclosure) {
      return `Error: Enclosure named ${enclosureName} not found.`;
    }

    if (enclosure.dinosaurs.length >= enclosure.capacity) {
      return `Error: Enclosure ${enclosureName} has reached its maximum capacity.`;
    }

    // Check that predators are not mixed with herbivores
    if (enclosure.dinosaurs.length > 0) {
      const existingDiet = enclosure.dinosaurs[0].diet;
      if (dino.diet === "carnivore" && existingDiet === "herbivore") {
        return "Error: Predators cannot be placed with herbivores!";
      }
      if (dino.diet === "herbivore" && existingDiet === "carnivore") {
        return "Error: Herbivores cannot be placed with predators!";
      }
    }

    // Remove the dinosaur from its previous enclosure, if it was assigned to one
    this.enclosures.forEach(e => {
      const index = e.dinosaurs.findIndex(d => d.name === dinoName);
      if (index !== -1) {
        e.dinosaurs.splice(index, 1);
      }
    });

    // Assign the dinosaur to the new enclosure
    enclosure.dinosaurs.push(dino);
    dino.enclosure = enclosureName;

    return `${dinoName} has been assigned to enclosure ${enclosureName}.`;
  }

  getEnclosureReport(enclosureName) {
    const enclosure = this.enclosures.find(e => e.name === enclosureName);

    if (!enclosure) {
      return `Error: Enclosure named ${enclosureName} not found.`;
    }

    let report = `=== ENCLOSURE REPORT: ${enclosure.name} ===
Capacity: ${enclosure.dinosaurs.length}/${enclosure.capacity}
Status: ${enclosure.status}
Dinosaurs:\n`;

    if (enclosure.dinosaurs.length === 0) {
      report += "No dinosaurs in this enclosure.";
    } else {
      enclosure.dinosaurs.forEach(dino => {
        report += `- ${dino.name} (${dino.species}): Health: ${dino.health}%, Hunger: ${dino.hunger}%\n`;
      });
    }

    return report;
  }
}

// Class for dinosaurs
class Dinosaur {
  constructor(name, species, diet) {
    this.name = name;
    this.species = species;
    this.diet = diet;
    this.health = 100;
    this.hunger = 50;
    this.enclosure = null; // Name of the enclosure the dinosaur is assigned to
  }
}

// Class for enclosures
class Enclosure {
  constructor(name, capacity, security) {
    this.name = name;
    this.capacity = capacity;
    this.security = security; // security level
    this.status = "Operational";
    this.dinosaurs = []; // List of dinosaurs in the enclosure
  }
}

// Using the management system
const parkManager = new DinosaurManager();

// Creating enclosures
const carnivoreEnclosure = new Enclosure("Paddock A", 3, "Maximum");
const herbivoreEnclosure = new Enclosure("Paddock B", 5, "Standard");

parkManager.addEnclosure(carnivoreEnclosure);
parkManager.addEnclosure(herbivoreEnclosure);

// Creating dinosaurs
const rex = new Dinosaur("Rex", "Tyrannosaurus", "carnivore");
const blue = new Dinosaur("Blue", "Velociraptor", "carnivore");
const trixie = new Dinosaur("Trixie", "Triceratops", "herbivore");
const spike = new Dinosaur("Spike", "Stegosaurus", "herbivore");

parkManager.addDinosaur(rex);
parkManager.addDinosaur(blue);
parkManager.addDinosaur(trixie);
parkManager.addDinosaur(spike);

// Assigning dinosaurs to enclosures
console.log(parkManager.assignDinosaurToEnclosure("Rex", "Paddock A"));
console.log(parkManager.assignDinosaurToEnclosure("Blue", "Paddock A"));
console.log(parkManager.assignDinosaurToEnclosure("Trixie", "Paddock B"));
console.log(parkManager.assignDinosaurToEnclosure("Spike", "Paddock B"));

// Attempting to assign a herbivore to the predator enclosure
console.log(parkManager.assignDinosaurToEnclosure("Trixie", "Paddock A"));

// Displaying the reports
console.log(parkManager.getEnclosureReport("Paddock A"));
console.log(parkManager.getEnclosureReport("Paddock B"));

Summary

Objects are a fundamental part of the JavaScript language and let us model complex data structures and behavior. In Jurassic Park we use them to represent everything - from dinosaurs to the system that manages the whole park.

We have several ways to create objects:

  1. Object literals - the simplest way, ideal for single, unique objects
  2. Constructor functions - when we need to create many similar objects
  3. Classes (ES6+) - a modern, readable syntax for creating object templates with inheritance
  4. Object.create() - creating objects with a specified prototype
  5. Factory functions - functions that return new objects, an alternative to constructors

The choice of a particular technique depends on the situation and the needs of the project. In complex applications, like our Jurassic Park management system, we most often use a combination of these techniques.

Code for this lesson: index.js
// Objects - creation - Jurassic Park
console.log("JavaScript Objects Laboratory");
console.log("Creating and constructing objects\n");

// ===========================================
// 1. OBJECT LITERALS (the simplest way)
// ===========================================
console.log("=== 1. Object literals ===");

// Basic object
const dinosaur1 = {
  name: "T-Rex",
  species: "Tyrannosaurus Rex",
  age: 8,
  weight: 8000,
  carnivore: true
};

console.log("Dinosaur 1:");
console.log(`   Name: ${dinosaur1.name}`);
console.log(`   Species: ${dinosaur1.species}`);
console.log(`   Age: ${dinosaur1.age} years`);

// Object with methods
const dinosaur2 = {
  name: "Blue",
  species: "Velociraptor",
  speed: 40,

  // Traditional method
  roar: function() {
    return `${this.name} roars: SHREEK!`;
  },

  // Shorthand method (ES6)
  run() {
    return `${this.name} runs at a speed of ${this.speed} km/h`;
  }
};

console.log("\nDinosaur 2:");
console.log(`   ${dinosaur2.roar()}`);
console.log(`   ${dinosaur2.run()}`);

// ===========================================
// 2. FUNCTION CONSTRUCTORS
// ===========================================
console.log("\n=== 2. Constructor functions ===");

function Dinosaur(name, species, age, weight, carnivore) {
  this.name = name;
  this.species = species;
  this.age = age;
  this.weight = weight;
  this.carnivore = carnivore;

  this.getInfo = function() {
    return `${this.name} (${this.species}) - ${this.age} years, ${this.weight}kg`;
  };

  this.roar = function() {
    return `${this.name} says: ROAARRR!`;
  };
}

const trex = new Dinosaur("Rexy", "T-Rex", 8, 8000, true);
const trike = new Dinosaur("Trike", "Triceratops", 7, 9000, false);

console.log("\nCreated via constructor:");
console.log(`   ${trex.getInfo()}`);
console.log(`   ${trex.roar()}`);
console.log(`   ${trike.getInfo()}`);

// ===========================================
// 3. Object.create()
// ===========================================
console.log("\n=== 3. Object.create() ===");

const dinoPrototype = {
  getInfo() {
    return `${this.name} (${this.species})`;
  },

  roar() {
    return `${this.name}: ROAARRR!`;
  }
};

const velociraptor = Object.create(dinoPrototype);
velociraptor.name = "Charlie";
velociraptor.species = "Velociraptor";
velociraptor.age = 5;

console.log("\nCreated via Object.create():");
console.log(`   ${velociraptor.getInfo()}`);
console.log(`   ${velociraptor.roar()}`);

// ===========================================
// 4. ES6 CLASSES
// ===========================================
console.log("\n=== 4. ES6 Classes ===");

class DinosaurClass {
  constructor(name, species, age, weight, carnivore) {
    this.name = name;
    this.species = species;
    this.age = age;
    this.weight = weight;
    this.carnivore = carnivore;
  }

  getInfo() {
    return `${this.name} (${this.species}) - ${this.age} years, ${this.weight}kg`;
  }

  roar() {
    return `${this.name} says: ROAARRR!`;
  }

  isHeavy() {
    return this.weight > 1000;
  }
}

const stego = new DinosaurClass("Stego", "Stegosaurus", 6, 5000, false);
const brachio = new DinosaurClass("Brachio", "Brachiosaurus", 10, 50000, false);

console.log("\nCreated via class:");
console.log(`   ${stego.getInfo()}`);
console.log(`   Is it heavy? ${stego.isHeavy()}`);
console.log(`   ${brachio.getInfo()}`);
console.log(`   Is it heavy? ${brachio.isHeavy()}`);

// ===========================================
// 5. FACTORY FUNCTIONS
// ===========================================
console.log("\n=== 5. Factory functions ===");

function createDinosaur(name, species, options = {}) {
  return {
    name,
    species,
    age: options.age || 5,
    weight: options.weight || 100,
    carnivore: options.carnivore || false,
    sector: options.sector || "A",

    getInfo() {
      return `${this.name} (${this.species}) - Sector ${this.sector}`;
    },

    feed() {
      console.log(`Feeding ${this.name}`);
    }
  };
}

const dilo = createDinosaur("Dilo", "Dilophosaurus", {
  age: 4,
  weight: 400,
  carnivore: true,
  sector: "E"
});

console.log("\nCreated via factory:");
console.log(`   ${dilo.getInfo()}`);
dilo.feed();

// ===========================================
// 6. NESTED OBJECTS
// ===========================================
console.log("\n=== 6. Nested objects ===");

const park = {
  name: "Jurassic Park",
  location: "Isla Nublar",

  sectors: {
    A: { name: "Carnivore Zone", capacity: 5, current: 2 },
    B: { name: "Raptor Pen", capacity: 10, current: 3 },
    C: { name: "Herbivore Valley", capacity: 20, current: 8 }
  },

  stats: {
    totalDinosaurs: 13,
    totalVisitors: 1500,
    securityLevel: "HIGH"
  },

  getReport() {
    console.log(`\nPark report for ${this.name}:`);
    console.log(`   Location: ${this.location}`);
    console.log(`   Dinosaurs: ${this.stats.totalDinosaurs}`);
    console.log(`   Visitors: ${this.stats.totalVisitors}`);
    console.log(`   Security: ${this.stats.securityLevel}`);
  }
};

park.getReport();

console.log("\nSectors:");
Object.entries(park.sectors).forEach(([key, sector]) => {
  console.log(`   ${key}: ${sector.name} - ${sector.current}/${sector.capacity}`);
});

// ===========================================
// 7. GETTERS AND SETTERS
// ===========================================
console.log("\n=== 7. Getters and setters ===");

class ManagedDinosaur {
  constructor(name, species, health) {
    this.name = name;
    this.species = species;
    this._health = health; // Private property (by convention)
  }

  // Getter
  get health() {
    return this._health;
  }

  // Setter with validation
  set health(value) {
    if (value < 0) value = 0;
    if (value > 100) value = 100;
    this._health = value;
    console.log(`   Health of ${this.name} changed to ${this._health}%`);
  }

  get status() {
    if (this._health >= 80) return "Healthy";
    if (this._health >= 50) return "Medium";
    return "Critical";
  }
}

const managedDino = new ManagedDinosaur("Rex", "T-Rex", 75);
console.log(`\n${managedDino.name}:`);
console.log(`   Health: ${managedDino.health}%`);
console.log(`   Status: ${managedDino.status}`);

managedDino.health = 95;
console.log(`   New status: ${managedDino.status}`);

managedDino.health = 150; // Will be capped at 100
console.log(`   Status after exceeding the limit: ${managedDino.status}`);

// ===========================================
// 8. STATIC METHODS AND PROPERTIES
// ===========================================
console.log("\n=== 8. Static methods and properties ===");

class DinoSpecies {
  static species = [
    "Tyrannosaurus Rex",
    "Velociraptor",
    "Triceratops",
    "Stegosaurus",
    "Brachiosaurus"
  ];

  static isCarnivore(species) {
    const carnivores = ["Tyrannosaurus Rex", "Velociraptor", "Spinosaurus"];
    return carnivores.includes(species);
  }

  static getInfo(species) {
    const info = {
      "Tyrannosaurus Rex": { weight: 8000, period: "Cretaceous" },
      "Velociraptor": { weight: 80, period: "Cretaceous" },
      "Triceratops": { weight: 9000, period: "Cretaceous" }
    };
    return info[species] || { weight: "?", period: "?" };
  }

  static listAll() {
    console.log("\nAll species:");
    this.species.forEach((s, i) => {
      const carnivore = this.isCarnivore(s) ? "carnivore" : "herbivore";
      console.log(`   ${i + 1}. ${carnivore} ${s}`);
    });
  }
}

DinoSpecies.listAll();

console.log("\nChecking species:");
console.log(`   T-Rex carnivore? ${DinoSpecies.isCarnivore("Tyrannosaurus Rex")}`);
console.log(`   Triceratops carnivore? ${DinoSpecies.isCarnivore("Triceratops")}`);

const trexInfo = DinoSpecies.getInfo("Tyrannosaurus Rex");
console.log(`\nInfo about T-Rex: weight ${trexInfo.weight}kg, period ${trexInfo.period}`);

// ===========================================
// 9. INHERITANCE
// ===========================================
console.log("\n=== 9. Inheritance ===");

class Animal {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  breathe() {
    return `${this.name} breathes`;
  }

  getAge() {
    return `${this.name} is ${this.age} years old`;
  }
}

class Carnivore extends Animal {
  constructor(name, age, huntingSkill) {
    super(name, age);
    this.huntingSkill = huntingSkill;
    this.type = "Carnivore";
  }

  hunt() {
    return `${this.name} hunts (skill: ${this.huntingSkill}/10)`;
  }

  roar() {
    return `${this.name} roars: ROAARRR!`;
  }
}

class Herbivore extends Animal {
  constructor(name, age, plantPreference) {
    super(name, age);
    this.plantPreference = plantPreference;
    this.type = "Herbivore";
  }

  eat() {
    return `${this.name} eats ${this.plantPreference}`;
  }

  graze() {
    return `${this.name} peacefully grazes`;
  }
}

const rex = new Carnivore("Rexy", 8, 10);
const trico = new Herbivore("Trico", 7, "ferns");

console.log("\nCarnivore:");
console.log(`   ${rex.getAge()}`);
console.log(`   ${rex.breathe()}`);
console.log(`   ${rex.hunt()}`);
console.log(`   ${rex.roar()}`);

console.log("\nHerbivore:");
console.log(`   ${trico.getAge()}`);
console.log(`   ${trico.breathe()}`);
console.log(`   ${trico.eat()}`);
console.log(`   ${trico.graze()}`);

// ===========================================
// 10. COMPLEX EXAMPLE
// ===========================================
console.log("\n=== 10. Management system - complex example ===");

class ParkManagementSystem {
  constructor(parkName) {
    this.parkName = parkName;
    this.dinosaurs = new Map();
    this.nextId = 1;
  }

  addDinosaur(name, species, options = {}) {
    const dino = {
      id: this.nextId++,
      name,
      species,
      age: options.age || 5,
      weight: options.weight || 1000,
      health: options.health || 100,
      sector: options.sector || "A",
      carnivore: options.carnivore || false,
      fed: false,
      lastCheckup: new Date()
    };

    this.dinosaurs.set(dino.id, dino);
    console.log(`Added: ${name} (#${dino.id})`);
    return dino.id;
  }

  getDinosaur(id) {
    return this.dinosaurs.get(id);
  }

  removeDinosaur(id) {
    const dino = this.dinosaurs.get(id);
    if (dino) {
      this.dinosaurs.delete(id);
      console.log(`Removed: ${dino.name} (#${id})`);
      return true;
    }
    return false;
  }

  feedDinosaur(id) {
    const dino = this.dinosaurs.get(id);
    if (dino) {
      dino.fed = true;
      console.log(`Fed: ${dino.name}`);
    }
  }

  updateHealth(id, newHealth) {
    const dino = this.dinosaurs.get(id);
    if (dino) {
      dino.health = Math.max(0, Math.min(100, newHealth));
      console.log(`Updated health of ${dino.name}: ${dino.health}%`);
    }
  }

  getStats() {
    const dinos = Array.from(this.dinosaurs.values());

    return {
      total: dinos.length,
      carnivores: dinos.filter(d => d.carnivore).length,
      avgHealth: (dinos.reduce((sum, d) => sum + d.health, 0) / dinos.length).toFixed(1),
      fed: dinos.filter(d => d.fed).length,
      bySector: dinos.reduce((acc, d) => {
        acc[d.sector] = (acc[d.sector] || 0) + 1;
        return acc;
      }, {})
    };
  }

  displayReport() {
    console.log(`\n============================================================`);
    console.log(`PARK REPORT: ${this.parkName}`);
    console.log("=".repeat(60));

    const stats = this.getStats();
    console.log("\nStatistics:");
    console.log(`   Total dinosaurs: ${stats.total}`);
    console.log(`   Carnivores: ${stats.carnivores}`);
    console.log(`   Average health: ${stats.avgHealth}%`);
    console.log(`   Fed: ${stats.fed}/${stats.total}`);

    console.log("\nBreakdown by sector:");
    Object.entries(stats.bySector).sort().forEach(([sector, count]) => {
      console.log(`   Sector ${sector}: ${count}`);
    });

    console.log("\nDinosaur list:");
    Array.from(this.dinosaurs.values())
      .sort((a, b) => a.id - b.id)
      .forEach(dino => {
        const icon = dino.carnivore ? "carnivore" : "herbivore";
        const fedStatus = dino.fed ? "√" : "Γ—";
        console.log(`   #${dino.id} ${icon} ${dino.name} (${dino.species})`);
        console.log(`       Sector ${dino.sector} | Health: ${dino.health}% | Fed: ${fedStatus}`);
      });
  }
}

// System demonstration
console.log();
const parkSystem = new ParkManagementSystem("Isla Nublar");

const id1 = parkSystem.addDinosaur("Rexy", "T-Rex", { age: 8, weight: 8000, sector: "A", carnivore: true });
const id2 = parkSystem.addDinosaur("Blue", "Velociraptor", { age: 5, weight: 80, sector: "B", carnivore: true, health: 100 });
const id3 = parkSystem.addDinosaur("Charlie", "Velociraptor", { age: 5, weight: 80, sector: "B", carnivore: true, health: 85 });
const id4 = parkSystem.addDinosaur("Trike", "Triceratops", { age: 7, weight: 9000, sector: "C", health: 70 });
const id5 = parkSystem.addDinosaur("Stego", "Stegosaurus", { age: 6, weight: 5000, sector: "C" });

console.log();
parkSystem.feedDinosaur(id1);
parkSystem.feedDinosaur(id2);
parkSystem.updateHealth(id4, 85);

parkSystem.displayReport();

console.log("\nCongratulations! You've mastered creating objects!");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What are the two ways to access object properties in JavaScript?

  2. 2. What does the 'new' keyword do before calling a constructor function?

Hands-on tasks in the game

  • Click in order

    Arrange the elements of creating a dinosaur object with a method:

  • Code editor

    Create an object dinosaur with the properties name: 'Rexy', species: 'Tyrannosaurus Rex', age: 25 and isCarnivore: true, and with a nested object stats that has the property health: 95. After creating the object, add a property enclosure with the value 'Zone A'. Display name using dot notation and species using bracket notation in the console.

  • Horizontal ordering

    Arrange the elements of creating an object with a literal:

  • Click in order

    Arrange the elements of an object declaration with properties:

  • Horizontal ordering

    Arrange the elements of an object declaration in JavaScript

  1. QuestionObject Basics - Accessing Properties
  2. QuestionObject Basics - Constructor with new
  3. Click in orderObject Basics - Creating with Literals
  4. Coding taskCreating Objects
  5. Put in orderObject Literal
  6. Click in orderSorting: Object Declaration
  7. Put in orderObject Literal Syntax

Useful articles