🟨 JavaScript tutorial for beginners · Class 9 · Lesson 1 of 18 · Free
Objects & Classes – Build Your Own Blueprints in JavaScript
⏱ About 35 minutes · ▶ run real JavaScript here — nothing to install · no sign-in
In this lesson you will
- Create objects with properties and methods, and use this inside them
- Write a class with a constructor and make many objects from it with new
- Extend a class with extends and super to reuse code
Your class has 40 students. Each one has a name, a roll number and marks in three subjects. Writing 120 separate variables would be a nightmare. In this lesson you will pack each student into one object, and then build a class that makes as many students as you like.
How do I make an object in JavaScript?
In Class 8 Lesson 10 you met objects. An object keeps related data together under one name. Each piece of data is a property: a key and a value.
You read a property with a dot (`student.name`) or with square brackets (`student["name"]`). Brackets are useful when the key is inside a variable.
You can change a property or add a new one at any time. Even with `const`, the object's insides can change. `const` only stops you from pointing the name at a different object.
▶const student = {2 name: "Asha",3 roll: 12,4 marks: { maths: 92, science: 88 }5};6console.log(student.name);7console.log(student.marks.maths);89const subject = "science";10console.log(student.marks[subject]);1112student.roll = 14;13student.house = "Green";14console.log(student);
No variables yet.
▌✏️ Change this code and run it yourself
Asha9288{ name: "Asha", roll: 14, marks: { maths: 92, science: 88 }, house: "Green" }
💡 Try it: add a third subject, english: 79, and print student.marks.
How do I add methods and use this in a JavaScript object?
A property can also hold a function. A function inside an object is called a method. It is an action the object can do.
Inside a method, `this` means "the object that called me". So `this.runs` reads the runs of this very batter, not some other one.
Why not just write `batter.runs`? Because with `this`, the same method works even if you copy it to another object.
Rohit: 11 runs off 3 ballsStrike rate: 366.7
💡 hit(runs) { … } is the short way to write hit: function (runs) { … }.
What is a class in JavaScript and why do I need one?
Now imagine 11 batters. Copying that object 11 times is slow and easy to get wrong. A class is a blueprint (like a cutter for making many cookies of the same shape).
The `constructor` runs once each time you write `new`. It fills in the new object's properties using `this`.
Methods written in the class are shared by every object made from it. Each object (an instance) keeps its own data.
1class Student {2 constructor(name, maths, science) {3 this.name = name;4 this.maths = maths;5 this.science = science;6 }7 total() {8 return this.maths + this.science;9 }10}▶const a = new Student("Asha", 92, 88);12const r = new Student("Rohan", 67, 74);13console.log(a.name, a.total());14console.log(r.name, r.total());15console.log(r);
No variables yet.
▌✏️ Change this code and run it yourself
Asha 180Rohan 141Student { name: "Rohan", maths: 67, science: 74 }
💡 Watch the steps: the constructor runs twice, once for each new Student.
How do JavaScript class methods change an object's data safely?
A good class does not just store data. Its methods also guard the data, so it never becomes wrong.
This wallet will not let you spend more than you have. The check lives in one place, the `spend` method, so every wallet follows the same rule.
A method can also `return this` or return a message. Here `spend` returns true or false, so the caller knows if it worked.
1class Wallet {2 constructor(owner, balance) {3 this.owner = owner;4 this.balance = balance;5 }6 spend(amount, item) {7 if (amount > this.balance) {8 console.log(`${this.owner}: not enough for ${item}!`);9 return false;10 }11 this.balance = this.balance - amount;12 console.log(`${this.owner} bought ${item}. Left: ₹${this.balance}`);13 return true;14 }15}▶const w = new Wallet("Riya", 100);17w.spend(30, "samosa");18w.spend(80, "comic book");19w.spend(50, "notebook");
No variables yet.
▌✏️ Change this code and run it yourself
Riya bought samosa. Left: ₹70Riya: not enough for comic book!Riya bought notebook. Left: ₹20
💡 Try it: make a second wallet for your friend with ₹500 and spend from both.
What do extends and super mean in a JavaScript class?
Sometimes one kind of thing is a special version of another. A captain is a player, plus a little extra. `extends` says "start with everything the Player class has".
Inside the new constructor you must call `super(...)` first. It runs the parent's constructor, so `name` and `runs` are set up as before.
The child class can add new methods, or replace a parent method with its own version. This is called inheritance.
Kavya has scored 45 runs.Arjun has scored 72 runs. Captain of Blue House!
💡 super.intro() calls the parent's intro, so the captain's message reuses it.
How can a JavaScript class control part of a web page?
Classes are great for things on a page that have their own data and actions. Here each counter keeps its own count and its own label.
We make two counters from one class: one for tiffins packed, one for water bottles. Click the buttons on the page to see them work.
The `render` method copies the object's data to the page. Whenever the data changes, call `render` again.
📄 HTML of the page (tap to see / edit)
Tiffins packed: 1
💡 The arrow function () => this.add() keeps this pointing at the counter object.
🤔 Predict the output
Think like JavaScript: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
const a = { runs: 10 };
const b = a;
b.runs = 50;
console.log(a.runs);Question 2. What does this print?
class Team {
constructor(name) {
this.name = name;
this.score = 0;
}
add(runs) {
this.score = this.score + runs;
}
}
const t = new Team("India");
t.add(4);
t.add(6);
console.log(t.score);Question 3. What does this print?
const pet = { name: "Moti", type: "dog" };
console.log(pet.age);🧩 Your challenge
Build a pocket-money tracker with a class. Make a class PocketMoney with a constructor(owner) that starts balance at 0 and history as an empty array. Add methods add(amount, note) and spend(amount, note) that change the balance and push a line into history (do not spend more than the balance — print a warning instead). Add report() that prints every history line and then the balance. Expected output for the starter's test lines: Not enough money for a cricket bat! +₹500 Diwali gift -₹120 movie ticket +₹50 helped at home Balance for Meera: ₹430
Not enough money for a cricket bat! +₹500 Diwali gift -₹120 movie ticket +₹50 helped at home Balance for Meera: ₹430
⚠️ Common mistakes (and how to fix them)
❌ Wrong
class Student {
constructor(name) {
this.name = name;
}
}
const s = Student("Asha");
console.log(s.name);TypeError: Class constructor Student cannot be invoked without 'new'
✅ Right
class Student {
constructor(name) {
this.name = name;
}
}
const s = new Student("Asha");
console.log(s.name);A class is not a normal function. You must write new before it, so JavaScript creates a fresh object for the constructor to fill.
❌ Wrong
class Box {
constructor(sweets) {
this.sweets = sweets;
}
count() {
return sweets.length;
}
}
const box = new Box(["ladoo", "barfi"]);
console.log(box.count());ReferenceError: sweets is not defined
✅ Right
class Box {
constructor(sweets) {
this.sweets = sweets;
}
count() {
return this.sweets.length;
}
}
const box = new Box(["ladoo", "barfi"]);
console.log(box.count());Inside a method, the object's data is this.sweets. Plain sweets was only a constructor parameter, and it is gone after the constructor finishes.
❌ Wrong
const singer = {
name: "Ananya",
greet: () => `Hi, I am ${this.name}`
};
console.log(singer.greet());TypeError: Cannot read properties of undefined (reading 'name')
✅ Right
const singer = {
name: "Ananya",
greet() {
return `Hi, I am ${this.name}`;
}
};
console.log(singer.greet());An arrow function does not get its own this, so this is not the object. Use the normal method style greet() { … } for methods.
📌 Remember
- An object groups related properties (data) and methods (actions) under one name.
- Inside a method, this means the object that called the method.
- A class is a blueprint; new ClassName(...) runs the constructor and makes an instance.
- Methods can guard data, for example by refusing to spend more than the balance.
- extends reuses a parent class; call super(...) first in the child's constructor.
- Two names can point to the same object, so changing one changes "both".
Finished the quiz and the challenge?
Questions students ask
What is the difference between an object and a class in JavaScript?
A class is the blueprint, and an object is a real thing made from it. One Student class can make 40 student objects, each with its own name and marks. You can also make a single object directly with { } when you need only one.
What does this mean in JavaScript?
Inside a method, this is the object the method was called on. In batter.hit(4), this is batter. Arrow functions are different: they take this from the code around them, so do not use them as object methods.
Is JavaScript an object-oriented language?
Yes, JavaScript supports object-oriented programming. Almost everything you use, like arrays and strings, is an object with methods. The class keyword (added in 2015) gives a clean way to write blueprints.
Do I need classes for every JavaScript program?
No. For small scripts, plain objects and functions are enough. Classes help when you need many similar things with the same actions, like players in a game or items in a shop.