The JavaScript Handbook: Object-Oriented Programming (OOP) is your essential guide to mastering OOP principles and practices in JavaScript. This comprehensive resource takes you from the basics of objects, properties, and methods to advanced concepts like inheritance, encapsulation, and polymorphism. With detailed explanations, hands-on exercises, and multiple-choice questions, this book offers a step-by-step approach to mastering the complexities of OOP.
Object-oriented programming is one of the most vital paradigms in modern development. It enables the creation of reusable, scalable, and maintainable code. This book focuses on the key concepts every developer must understand to thrive in web development and modern application design. You’ll explore constructor functions, prototypes, and ES6 classes in depth, learning how to build your own reusable object models.
The book’s practical approach is what sets it apart. You’ll work on coding exercises where you build objects, extend them with classes, and create methods that operate on them. Concepts like inheritance, polymorphism, and method chaining are broken down into clear, accessible language that demystifies even the most complex ideas. Each chapter features coding exercises with detailed solutions, ensuring you understand every step.
Beyond the theory, you’ll tackle real-world development challenges. You’ll see how OOP principles apply to common problems like data modeling, behavior encapsulation, and creating classes for front-end frameworks. The content is relevant for developers of all levels, from beginners to experienced professionals. It will prepare you to work with JavaScript frameworks like React, Vue.js, and Angular, where OOP skills are indispensable.
If you’re a developer seeking to deepen your knowledge of JavaScript or refine your understanding of object-oriented programming, this book is a must-have. It offers everything you need to build, test, and master JavaScript OOP concepts with confidence.
JavaScript Handbook Object-Oriented Programming https://www.amazon.com/dp/B0DQXHLF7K or https://www.amazon.ca/dp/B0DQXHLF7K
JavaScript Handbook
Object-Oriented Programming (OOP)
Summary
The JavaScript Handbook: Object-Oriented Programming (OOP) provides a comprehensive guide to mastering OOP concepts in JavaScript. It starts with foundational principles like objects, constructors, and prototypes before progressing to advanced concepts like inheritance, polymorphism, and encapsulation.
Through clear explanations, coding exercises, and multiple-choice questions, readers gain hands-on experience and insight into building maintainable, scalable applications. Each chapter introduces a key OOP concept, explains how it works in practice, and challenges readers with real-world scenarios. Topics like method chaining, mixins, and ES6 classes are covered in depth.
By the end of the book, readers will have a solid foundation in OOP principles and the confidence to apply them to modern web development, particularly in frameworks like React, Vue.js, and Angular. The skills learned in this book are essential for building robust applications and understanding the underlying structure of modern JavaScript.
Introduction
Welcome to the JavaScript Handbook: Object-Oriented Programming (OOP). This book is your ultimate guide to mastering one of the most essential concepts in modern JavaScript development. Whether you’re a beginner taking your first steps into the world of OOP or an experienced developer looking to refine your skills, this book provides a structured path to deep understanding.
Object-oriented programming (OOP) is at the heart of many software development paradigms. It powers everything from modern frameworks to large-scale applications. By mastering OOP, you’ll be equipped to build scalable, maintainable, and efficient software.
This handbook begins with foundational concepts like objects and constructors, gradually leading you into advanced topics like inheritance, polymorphism, encapsulation, and method chaining. Each chapter includes theory, hands-on coding exercises, multiple-choice questions with explanations, and detailed solutions. You’ll learn not only how to write OOP-style code, but also why it matters.
Expect to build practical skills that you can immediately apply to your projects. By the end of this book, you’ll have a solid grasp of OOP, which is essential for working with frameworks, libraries, and large-scale applications.
Get ready to take your JavaScript development skills to the next level. Let’s dive in!
JavaScript Objects
Introduction to Objects
In JavaScript, objects are collections of key-value pairs. They are one of the most fundamental data types, enabling you to store, manipulate, and organize complex data. Almost everything in JavaScript (strings, numbers, arrays, functions) can be wrapped in an object form, and objects form the building blocks of the language’s powerful features.
Creating Objects
Object Literals: The most common way to create an object is using curly braces {} and defining properties inside them.
const person = {
name: “Alice”,
age: 30
};
Using new Object():
const obj = new Object();
obj.key = “value”;
Constructor Functions and Classes: More advanced ways to create objects.
Object Properties
Properties are key-value pairs. The key is usually a string (or Symbol), and the value can be any type: string, number, boolean, array, function, or another object.
const car = {
brand: “Toyota”,
model: “Corolla”,
year: 2020,
color: “blue”
};
- Accessing Properties:
- Dot notation: car.brand
- Bracket notation: car[“model”]
Modifying and Adding Properties:
car.color = “red”;
car.owner = “Alice”; // added new property
Deleting Properties:
delete car.year;
Object Methods
Methods are properties that hold function values. They allow objects to have behavior.
const mathOperations = {
x: 10,
y: 5,
add: function() {
return this.x + this.y;
},
multiply() {
return this.x * this.y;
}
};
console.log(mathOperations.add()); // 15
console.log(mathOperations.multiply()); // 50
- Notice the use of this to refer to the current object’s properties.
- From ES6 onward, you can define methods without the function keyword.
Property Descriptors and Object Methods
JavaScript provides built-in methods like Object.keys(), Object.values(), and Object.entries() for iterating over object properties:
const user = { name: “John”, age: 25 };
console.log(Object.keys(user)); // [“name”, “age”]
console.log(Object.values(user)); // [“John”, 25]
console.log(Object.entries(user)); // [[“name”, “John”], [“age”, 25]]
Object Copying and Reference
Objects are reference types. Assigning one object to another variable does not create a copy; it creates a reference.
const original = { a: 1 };
const copy = original;
copy.a = 2;
console.log(original.a); // 2 (both point to the same object)
- To create a shallow copy:
Use Object.assign():
const shallowCopy = Object.assign({}, original);
Use the spread operator:
const shallowCopy2 = { …original };
Checking Properties
in operator:
if (“name” in user) console.log(“user has a name”);
hasOwnProperty() method:
user.hasOwnProperty(“age”); // true
Multiple Choice Questions (With Answers and Explanations)
- How do you create an object literal in JavaScript?
A. const obj = {};
B. const obj = new Object();
C. const obj = new {};
D. const obj = ();
Answer: A
Explanation: {} is the literal syntax for creating an object. - Which of these is a valid object property access using dot notation?
A. obj[“key”]
B. obj.key
C. obj(key)
D. obj->key
Answer: B
Explanation: Dot notation uses obj.key. - If const car = {brand: “Ford”}; const anotherCar = car; anotherCar.brand = “Toyota”; What is car.brand?
A. “Ford”
B. “Toyota”
C. undefined
D. ReferenceError
Answer: B
Explanation: Both car and anotherCar reference the same object. - How to delete a property age from person object?
A. remove person.age;
B. person.age = undefined;
C. delete person.age;
D. person.clear(age);
Answer: C
Explanation: The delete operator removes a property from an object. - To check if property “name” exists in user, which is correct?
A. “name” in user
B. user.hasOwn(“name”)
C. propertyExists(user.name)
D. typeof user.name === “exists”
Answer: A
Explanation: “propertyName” in object checks property existence. - Which method returns an array of keys of an object?
A. Object.keys(obj)
B. Object.values(obj)
C. Object.entries(obj)
D. Object.getKeys(obj)
Answer: A
Explanation: Object.keys() returns an array of the object’s keys. - In an object method, this refers to:
A. The global object
B. The object the method is called on
C. Always window
D. this is undefined in methods
Answer: B
Explanation: In a method, this refers to the object itself. - What is the result of Object.values({x:10,y:20})?
A. [“x”,”y”]
B. [10,20]
C. [[“x”,10],[“y”,20]]
D. {x:10,y:20}
Answer: B
Explanation: Object.values() returns an array of property values. - Object.entries(user) returns:
A. An array of keys
B. An array of values
C. An array of [key, value] pairs
D. A single value
Answer: C
Explanation: Object.entries() returns an array of [key, value] arrays. - What does Object.assign(target, source) do?
A. Merges properties of source into target, returning target
B. Creates a deep clone of source
C. Deletes properties from target
D. Does nothing
Answer: A
Explanation: Object.assign() copies properties from source to target. - How can you define a method inside an object from ES6 onward without function keyword?
A. method() { … }
B. function method() {…}
C. :method = () => {}
D. ~method() {…}
Answer: A
Explanation: Shorthand method definition: methodName() { … }. - Which operator checks if “prop” is a property of obj?
A. obj.prop
B. “prop” in obj
C. prop in obj (without quotes)
D. obj.hasProperty(prop)
Answer: B
Explanation: “prop” in obj checks property existence. - What does delete obj.key; return if key existed?
A. true
B. false
C. undefined
D. It throws an error
Answer: A
Explanation: delete returns true if the property was successfully deleted. - If const person = {name:”Bob”}; person.age=25; what is person after these operations?
A. {name:”Bob”}
B. {name:”Bob”, age:25}
C. {name:”Bob”, age:undefined}
D. Throws error
Answer: B
Explanation: Adding a property just adds it: {name:”Bob”, age:25}. - Which statement about objects is true?
A. Object keys must be numbers
B. Object keys are always converted to strings
C. You cannot add properties after creation
D. Objects are immutable
Answer: B
Explanation: Keys in objects are strings (or Symbols), numeric keys become strings. - If you do const a = {}; const b = a; and then b.newProp = 123; what’s in a?
A. {}
B. {newProp:123}
C. undefined
D. {newProp:undefined}
Answer: B
Explanation: a and b reference the same object, so a shows the new property. - hasOwnProperty() checks if:
A. The object has the property defined directly on it, not in the prototype chain
B. The object has the property anywhere in the prototype chain
C. The property value is not null
D. The property key is numeric
Answer: A
Explanation: hasOwnProperty() checks directly on the object, not inherited properties. - To create a shallow copy of an object, which syntax is correct?
A. const copy = {…original};
B. const copy = *original;
C. const copy = original;
D. const copy = original.clone();
Answer: A
Explanation: Spread syntax {…original} creates a shallow copy. - If you console.log(Object.keys({a:1,b:2})), what is output?
A. {a:1,b:2}
B. [“1″,”2”]
C. [“a”,”b”]
D. [[“a”,1],[“b”,2]]
Answer: C
Explanation: Object.keys() returns [“a”,”b”]. - Object.freeze(obj) does what?
A. Deletes all properties
B. Prevents adding, removing, or changing properties
C. Only prevents adding new properties
D. Returns a new object
Answer: B
Explanation: Object.freeze() makes the object immutable.
10 Coding Exercises with Full Solutions and Explanations
1. Create and Access Object Properties
Problem:
Create an object book with properties title and author. Log the title using dot notation.
Solution:
const book = {
title: “1984”,
author: “George Orwell”
};
console.log(book.title); // “1984”
Explanation:
We defined an object literal and accessed a property using dot notation.
2. Add and Delete Properties
Problem:
Create an object car with brand = “Honda”. Add a property model = “Civic” and then delete brand. Log the resulting object.
Solution:
const car = { brand: “Honda” };
car.model = “Civic”;
delete car.brand;
console.log(car); // { model: “Civic” }
Explanation:
We added model and then removed brand, leaving {model:”Civic”}.
3. Object Method Using this
Problem:
Create an object calculator with properties a=5, b=3, and a method sum that returns a+b. Log the result of calculator.sum().
Solution:
const calculator = {
a: 5,
b: 3,
sum() {
return this.a + this.b;
}
};
console.log(calculator.sum()); // 8
Explanation:
Method uses this to access object’s properties.
4. Check Property Existence
Problem:
Create user = { name: “Alice”, age: 25 }. Check if age is in user and log “Has age” if true.
Solution:
const user = { name: “Alice”, age: 25 };
if (“age” in user) {
console.log(“Has age”); // “Has age”
}
Explanation:
“age” in user returns true, so we log “Has age”.
5. Iterate Over Object Keys
Problem:
Given const obj = {x:10,y:20,z:30}, use Object.keys and a loop to log each key and its value.
Solution:
const obj = { x: 10, y: 20, z: 30 };
const keys = Object.keys(obj);
for (let key of keys) {
console.log(key, obj[key]);
}
// x 10
// y 20
// z 30
Explanation:
We loop over keys and access values with bracket notation.
6. Object.values Example
Problem:
Given const fruit = { apple: 2, banana: 5 }; log the values array using Object.values().
Solution:
const fruit = { apple: 2, banana: 5 };
console.log(Object.values(fruit)); // [2,5]
Explanation:
Object.values() returns [2,5].
7. Object.entries Example
Problem:
Given const settings = { theme: “dark”, language: “en” }; use Object.entries() and a for-of loop to log key-value pairs.
Solution:
const settings = { theme: “dark”, language: “en” };
for (const [key, value] of Object.entries(settings)) {
console.log(key, value);
}
// theme dark
// language en
Explanation:
Object.entries() returns [[“theme”,”dark”],[“language”,”en”]].
8. Copy Object Using Spread
Problem:
Make a shallow copy of const original = {a:1, b:2} into copy and change copy.b=3 without affecting original.
Solution:
const original = { a: 1, b: 2 };
const copy = { …original };
copy.b = 3;
console.log(original.b); // 2
console.log(copy.b); // 3
Explanation:
Spread syntax creates a new object. Changing copy doesn’t affect original.
9. Using hasOwnProperty()
Problem:
Check if book has its own property “title” using hasOwnProperty.
Solution:
const book = { title: “Invisible Man”, author: “Ralph Ellison” };
console.log(book.hasOwnProperty(“title”)); // true
Explanation:
hasOwnProperty(“title”) returns true.
10. Adding a Method That Modifies an Object
Problem:
Create person = {name:”Bob”, greet() {console.log(“Hello “+this.name);}}. Call person.greet(). Then change person.name=”Charlie” and call person.greet() again.
Solution:
const person = {
name: “Bob”,
greet() {
console.log(“Hello ” + this.name);
}
};
person.greet(); // “Hello Bob”
person.name = “Charlie”;
person.greet(); // “Hello Charlie”
Explanation:
The method uses this.name, so changing name updates the greeting.
Conclusion
Objects are central to JavaScript, allowing you to store key-value pairs, define methods, and model complex data and behavior. Understanding how to create, access, modify, and iterate over objects, as well as how to use methods like Object.keys(), Object.values(), and Object.entries(), is fundamental. By mastering these concepts, you can structure your code more effectively and create robust data models within your JavaScript applications.