Objects & classes in Javascript
Created @October 29, 2025 12:48 PM
Objects & Classes in JavaScript — Easy
Study Notes
💡 1. What is an Object?
An object is a collection of key:value pairs.
Keys are strings (or symbols); values can be any type (number, string, array,
function, etc.).
Objects group related data and behavior.
✨ Example
const person = {
name: "Janakiram",
age: 21,
greet: function() { console.log("Hi, I'm " + this.name); }
// shorthand method: greet() { ... }
};
🔍 Accessing Properties
console.log(person.name); // Dot notation
console.log(person["age"]); // Bracket notation
const key = "name";
console.log(person[key]); // Dynamic access
Objects & classes in Javascript 1
➕ Add / Update / Delete
person.city = "Chennai"; // Add
person.age = 22; // Update
delete person.city; // Delete
⚙️ 2. The this Keyword
this refers to the object that called the method.
In arrow functions, this is lexically bound (taken from outer scope).
const a = {
name: "A",
show() { console.log(this.name); }
};
const b = { name: "B", show: a.show };
a.show(); // A
b.show(); // B
⚠️ Don’t use arrow functions for object methods if they depend on this.
🧬 3. Prototype-Based Inheritance
Every object links to a prototype object ( [[Prototype]] ).
If a property isn’t found, JS looks up the prototype chain.
const proto = { greet() { console.log("hi"); } };
const obj = Object.create(proto);
obj.greet(); // via prototype
Objects & classes in Javascript 2
🏗️ 4. Constructor Functions & new
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.say = function() {
console.log("Hi, I'm " + this.name);
};
const p = new Person("Janakiram", 21);
p.say();
new creates a new object, binds this to it, and links it to the constructor’s
prototype.
🏫 5. ES6 class Syntax (Modern)
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
say() {
console.log(`Hi, I'm ${this.name}`);
}
static createGuest() {
return new Person("Guest", 0);
}
}
Objects & classes in Javascript 3
const p = new Person("Janakiram", 21);
p.say();
Person.createGuest();
👨💼 Inheritance
class Employee extends Person {
constructor(name, age, role) {
super(name, age);
this.role = role;
}
info() { console.log(`${this.name} is a ${this.role}`); }
}
🔒 Private Fields & Methods
class Counter {
#count = 0;
increment() { this.#count++; }
get value() { return this.#count; }
}
🧩 6. Getters & Setters
const user = {
first: "Janaki",
last: "Ram",
get fullName() { return `${this.first} ${this.last}`; },
Objects & classes in Javascript 4
set fullName(v) { [this.first, this.last] = v.split(" "); }
};
user.fullName = "Bala K";
console.log(user.fullName); // Bala K
🧰 7. Useful Object Helpers
Function Purpose
Object.keys(obj) Array of keys
Object.values(obj) Array of values
Object.entries(obj) Array of [key, value]
Object.assign(target, source) Copy properties
Object.create(proto) Create with prototype
Object.freeze(obj) Prevent modifications
Object.seal(obj) Prevent add/delete
Object.defineProperty() Configure property details
⚡ 8. Property Descriptors
const o = {};
Object.defineProperty(o, "x", {
value: 42,
writable: false,
enumerable: false,
configurable: false
});
💭 9. Best Practices
Objects & classes in Javascript 5
Use classes for structured, reusable blueprints.
Use factory functions for simple object creation.
Avoid mutating shared prototypes.
Prefer const for objects (prevents reassignment).
Define shared methods on prototypes to save memory.
⚡ 10. Memory Tip
Methods shared across instances (on prototype) use less memory than
redefining them in constructors.
🎯 Destructuring in JavaScript
Destructuring allows unpacking values from arrays or objects into variables.
🧮 1. Array Destructuring
const arr = [1, 2, 3];
const [a, b, c] = arr;
const [x, , z] = arr; // Skip elements
const [p = 10, q = 20] = [5]; // Default values
const [head, ...tail] = [1,2,3,4]; // Rest
✅ Use cases:
Swap variables: [a, b] = [b, a]
Return multiple values: return [val1, val2]
🧱 2. Object Destructuring
Objects & classes in Javascript 6
const obj = { name: "J", age: 21, city: "Chennai" };
const { name, age } = obj;
const { name: fullName, city: town } = obj;
const { country = "India" } = obj;
const { name, ...rest } = obj;
📝 Notes:
Order does not matter.
Missing properties → undefined unless default is set.
🪆 3. Nested Destructuring
const data = { id: 1, user: { name: "A", contact: { phone: 123 } } };
const { user: { name, contact: { phone } } } = data;
✅ To avoid errors:
const { user: { name } = {} } = data;
🧰 4. Destructuring in Function Parameters
function greet({ name, age = 0 }) {
console.log(`Hi ${name}, age ${age}`);
}
greet({ name: "J" });
function printCoords([x, y]) {
console.log(x, y);
}
Objects & classes in Javascript 7
printCoords([1,2]);
⚡ 5. Spread + Destructuring
const a = [1,2,3];
const b = [0, ...a, 4];
const obj1 = { x:1, y:2 };
const obj2 = { ...obj1, z:3, y:10 };
🧩 Example Implementations
🪶 Object Method Using this
const book = {
title: "JS Guide",
author: "A",
details() {
console.log(`${this.title} by ${this.author}`);
}
};
book.details();
🐕 Class with Inheritance & Private Field
class Animal {
constructor(name) { this.name = name; }
speak() { console.log(`${this.name} makes a sound`); }
}
Objects & classes in Javascript 8
class Dog extends Animal {
#secret = "bones";
speak() { console.log(`${this.name} barks`); }
getSecret() { return this.#secret; }
}
const d = new Dog("Rex");
d.speak();
console.log(d.getSecret());
🧠 Destructuring Examples
const nums = [10, 20, 30];
const [one, two, three] = nums;
const user = { id: 1, name: "J", roles: ["admin", "user"] };
const { name, roles: [firstRole] } = user;
function signup({ username, email, role = "guest" }) {
console.log(username, email, role);
}
signup({ username: "jan", email: "
[email protected]" });
🚫 Common Pitfalls
1. Arrow this issue — arrow functions inherit outer this .
2. Destructuring undefined — check for parent existence.
3. Overwriting with spread — { ...a, ...b } overwrites same keys.
4. Using var — avoid it; prefer let or const .
Objects & classes in Javascript 9
5. Hardcoding object names in methods — use this for reusability.
⚡ Quick Cheat Sheet
Concept Syntax / Example
Object literal { key: value }
Access props obj.key or obj["key"]
Method shorthand say() {}
this Refers to calling object
Prototype Object.getPrototypeOf(obj)
Class class A { constructor(){} }
Inherit class B extends A { super(); }
Array destructure [a,b] = arr
Object destructure {x,y} = obj
Rename {x: newX}
Default {a=1} or [a=1]
Spread {...obj} or [...arr]
🧠 Practice Exercises
1. Fix a method to correctly use this and reuse across objects.
2. Create Person and Employee classes, add static method fromData() .
3. Destructure config = { host: 'h', port: 80, options: { secure: false } } to get host and secure = true
if missing.
4. Merge a and b without mutating a .
Objects & classes in Javascript 10