0% found this document useful (0 votes)
68 views10 pages

JavaScript Objects and Classes Guide

The document provides a comprehensive overview of objects and classes in JavaScript, covering key concepts such as object creation, property access, prototype-based inheritance, constructor functions, ES6 class syntax, and best practices. It also includes sections on destructuring, common pitfalls, and practical exercises. The information is structured to facilitate easy understanding and application of JavaScript object-oriented programming principles.

Uploaded by

kusujanakiram5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views10 pages

JavaScript Objects and Classes Guide

The document provides a comprehensive overview of objects and classes in JavaScript, covering key concepts such as object creation, property access, prototype-based inheritance, constructor functions, ES6 class syntax, and best practices. It also includes sections on destructuring, common pitfalls, and practical exercises. The information is structured to facilitate easy understanding and application of JavaScript object-oriented programming principles.

Uploaded by

kusujanakiram5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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() { [Link]("Hi, I'm " + [Link]); }
// shorthand method: greet() { ... }
};

🔍 Accessing Properties
[Link]([Link]); // Dot notation
[Link](person["age"]); // Bracket notation
const key = "name";
[Link](person[key]); // Dynamic access

Objects & classes in Javascript 1


➕ Add / Update / Delete
[Link] = "Chennai"; // Add
[Link] = 22; // Update
delete [Link]; // 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() { [Link]([Link]); }
};
const b = { name: "B", show: [Link] };

[Link](); // A
[Link](); // 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() { [Link]("hi"); } };


const obj = [Link](proto);
[Link](); // via prototype

Objects & classes in Javascript 2


🏗️ 4. Constructor Functions & new

function Person(name, age) {


[Link] = name;
[Link] = age;
}
[Link] = function() {
[Link]("Hi, I'm " + [Link]);
};

const p = new Person("Janakiram", 21);


[Link]();

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) {
[Link] = name;
[Link] = age;
}

say() {
[Link](`Hi, I'm ${[Link]}`);
}

static createGuest() {
return new Person("Guest", 0);
}
}

Objects & classes in Javascript 3


const p = new Person("Janakiram", 21);
[Link]();
[Link]();

👨‍💼 Inheritance
class Employee extends Person {
constructor(name, age, role) {
super(name, age);
[Link] = role;
}

info() { [Link](`${[Link]} is a ${[Link]}`); }


}

🔒 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 `${[Link]} ${[Link]}`; },

Objects & classes in Javascript 4


set fullName(v) { [[Link], [Link]] = [Link](" "); }
};

[Link] = "Bala K";


[Link]([Link]); // Bala K

🧰 7. Useful Object Helpers


Function Purpose
[Link](obj) Array of keys
[Link](obj) Array of values
[Link](obj) Array of [key, value]
[Link](target, source) Copy properties
[Link](proto) Create with prototype
[Link](obj) Prevent modifications
[Link](obj) Prevent add/delete
[Link]() Configure property details

⚡ 8. Property Descriptors
const o = {};
[Link](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 }) {
[Link](`Hi ${name}, age ${age}`);
}
greet({ name: "J" });

function printCoords([x, y]) {


[Link](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() {
[Link](`${[Link]} by ${[Link]}`);
}
};
[Link]();

🐕 Class with Inheritance & Private Field


class Animal {
constructor(name) { [Link] = name; }
speak() { [Link](`${[Link]} makes a sound`); }
}

Objects & classes in Javascript 8


class Dog extends Animal {
#secret = "bones";
speak() { [Link](`${[Link]} barks`); }
getSecret() { return this.#secret; }
}

const d = new Dog("Rex");


[Link]();
[Link]([Link]());

🧠 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" }) {


[Link](username, email, role);
}
signup({ username: "jan", email: "a@[Link]" });

🚫 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 [Link] or obj["key"]

Method shorthand say() {}

this Refers to calling object

Prototype [Link](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

Common questions

Powered by AI

In JavaScript, the 'this' keyword refers to the object from which a method was invoked. In traditional function expressions, 'this' points to the object that calls the function. However, in arrow functions, 'this' is lexically bound, meaning its value is taken from the outer enclosing context when the arrow function is defined, not where it is called. This behavior can lead to problems in object methods where 'this' is expected to point to the object itself. For instance, if an arrow function is used as a method in an object, 'this' will not refer to that object, preventing the method from accessing the object’s properties or methods correctly .

Destructuring in function parameters simplifies management of incoming data by directly unpacking elements into distinct variables with concise syntax. It supports assigning default values, ensuring function robustness in the absence of certain input data. For example, function greet({ name, age = 0 }) { ... } uses destructuring to neatly handle argument unpacking, assigning a default age if it's not provided. This reduces conditional checks inside functions, enhances readability, and prevents errors related to missing inputs by specifying defaults, fostering cleaner, more intuitive code .

Destructuring in function parameters allows you to extract values from objects or arrays directly within the parameter list of a function. This leads to concise and clear code by directly assigning input values to named parameters. For example, the function greet({ name, age = 0 }) { console.log(`Hi ${name}, age ${age}`); } uses destructuring to extract 'name' and 'age' from an object passed as an argument. If an age is not provided, it defaults to 0. Calling greet({ name: 'J' }) would output: Hi J, age 0 .

Destructuring in JavaScript is a syntax that allows unpacking values from arrays or objects into distinct variables. It resolves the problem of extracting multiple properties into individual variables more succinctly and readably. For object destructuring, consider const obj = { name: 'J', age: 21, city: 'Chennai' }; const { name, age } = obj; which efficiently extracts 'name' and 'age' into separate variables. This avoids repetitive code and manual property access through variables, leading to cleaner code .

Getters and setters in JavaScript define object properties that run functions upon being accessed or set, enhancing control over property access and modification. Getters compute a property value upon access, while setters execute code to set a value. For example, const user = { first: 'Janaki', last: 'Ram', get fullName() { return `${this.first} ${this.last}`; }, set fullName(v) { [this.first, this.last] = v.split(' '); } }; allows fullName to be accessed and modified, automatically updating or returning 'first' and 'last' values. Their purpose includes encapsulating internal data management, validation, and side effects, improving object integrity and encapsulation .

The ES6 class syntax provides a more structured and intuitive way to define classes compared to prototype-based syntax. It introduces a clearer, more concise syntax that resembles class-based languages, encapsulating constructor functions and methods within a class block. For example, using ES6 classes, you can define a class as: class Person { constructor(name, age) { this.name = name; this.age = age; } say() { console.log(`Hi, I'm ${this.name}`); } } This is simpler than using constructor functions and explicitly setting prototypes. Classes allow for static methods, inheritance using 'extends', and encapsulation with private fields and methods. This leads to more readable and maintainable code .

The `Object.defineProperty()` method configures an object’s property by specifying descriptors for its behavior, including value, writable, enumerable, and configurable flags. For instance, const o = {}; Object.defineProperty(o, 'x', { value: 42, writable: false, enumerable: false, configurable: false }); defines a property 'x' that is non-writable, non-enumerable, and non-configurable. Making a property non-configurable implies that its configuration cannot be altered later; the property cannot be deleted, nor can its attribute properties (writable, enumerable) be changed. This ensures a fixed behavior, preventing further modification or unintended deletion of critical properties .

In JavaScript, each object has a prototype, which is another object it inherits properties from. This is called prototype-based inheritance. If an object does not have a certain property or method, the JavaScript engine looks up the property chain to the object's prototype. This chain continues until it reaches a null prototype. A practical example is when you create an object using Object.create(proto), where 'proto' is the prototype object. For instance, with const proto = { greet() { console.log('hi'); } }; and const obj = Object.create(proto); accessing obj.greet() will invoke the greet method from proto because obj itself does not have a greet method .

Although the spread operator provides a concise syntax for merging objects by copying properties from source to target objects, it poses a risk of overwriting values of properties with the same keys. For example, const obj1 = { x:1, y:2 }; const obj2 = { ...obj1, z:3, y:10 }; overwrites y's value from obj1 with obj2's value. This risk can be mitigated by carefully ordering the objects in the merge process, where properties in later objects override those from earlier ones. Alternatively, strategic use of default value assignments and cautious structuring of properties before merging helps maintain data integrity .

Private fields in JavaScript classes are implemented using the '#' syntax before the field name. These fields are only accessible within the class they are declared in and cannot be accessed or altered from outside the class. For example, class Dog extends Animal { #secret = 'bones'; speak() { console.log(`${this.name} barks`); } getSecret() { return this.#secret; } } uses a private field '#secret'. This encapsulation prevents direct access and modification from outside, thereby maintaining integrity and restricting unintended interaction with the class internals. The benefits include enhanced security of class properties and methods, promoting better encapsulation and modular design .

You might also like