0
0
Javascriptprogramming~15 mins

Object creation in Javascript - Deep Dive

Choose your learning style9 modes available
Overview - Object creation
What is it?
Object creation in JavaScript means making a new object, which is a collection of related data and actions. Objects hold values as properties and functions as methods. They help organize and group information in a way that models real-world things or concepts. Creating objects lets programs store and manage complex data easily.
Why it matters
Without objects, JavaScript would only handle simple values like numbers or text, making it hard to represent real things like a person, a car, or a game character. Objects let us bundle data and behavior together, making code clearer and easier to manage. This helps build bigger, more useful programs that feel natural to work with.
Where it fits
Before learning object creation, you should understand basic JavaScript data types like strings, numbers, and variables. After mastering object creation, you can learn about object-oriented programming, classes, and prototypes to build more advanced and reusable code.
Mental Model
Core Idea
Creating an object is like making a labeled box that holds related things and actions together in one place.
Think of it like...
Imagine a toolbox where each tool has a name and a job. The toolbox is the object, the tools are properties (data), and the instructions on how to use them are methods (functions).
Object Creation
┌─────────────────────────┐
│        Object           │
│ ┌───────────────┐      │
│ │ property: value│      │
│ │ method() {}   │      │
│ └───────────────┘      │
└─────────────────────────┘
Build-Up - 7 Steps
1
FoundationCreating objects with curly braces
🤔
Concept: Objects can be created using curly braces {} with key-value pairs inside.
const person = { name: 'Alice', age: 30 }; // 'person' is an object with properties 'name' and 'age'.
Result
An object named 'person' with two properties: name = 'Alice' and age = 30.
Understanding that curly braces create a container for related data is the simplest way to start working with objects.
2
FoundationAccessing and modifying object properties
🤔
Concept: You can get or change values inside an object using dot notation or bracket notation.
console.log(person.name); // Outputs: Alice person.age = 31; // Changes age to 31 person['name'] = 'Bob'; // Changes name to Bob
Result
You can read and update object data easily using simple syntax.
Knowing how to access and change properties lets you interact with objects dynamically.
3
IntermediateCreating objects with Object.create()
🤔Before reading on: do you think Object.create() makes a copy of an object or sets up a prototype link? Commit to your answer.
Concept: Object.create() makes a new object that links to another object as its prototype, enabling inheritance.
const animal = { eats: true }; const rabbit = Object.create(animal); rabbit.jumps = true; console.log(rabbit.eats); // true (inherited)
Result
A new object 'rabbit' that inherits properties from 'animal' but can have its own properties too.
Understanding prototype linkage is key to grasping JavaScript's inheritance and object behavior.
4
IntermediateUsing constructor functions for objects
🤔Before reading on: do you think constructor functions return objects automatically or need explicit return? Commit to your answer.
Concept: Constructor functions create objects with shared structure and behavior using the 'new' keyword.
function Person(name, age) { this.name = name; this.age = age; } const alice = new Person('Alice', 30); console.log(alice.name); // Alice
Result
A new object 'alice' created with properties set by the constructor function.
Knowing constructor functions helps create many similar objects efficiently.
5
IntermediateAdding methods inside objects
🤔Before reading on: do you think methods inside objects can access other properties using 'this'? Commit to your answer.
Concept: Objects can have functions as properties called methods, which can use 'this' to refer to the object itself.
const car = { brand: 'Toyota', start() { return this.brand + ' started'; } }; console.log(car.start()); // Toyota started
Result
The method 'start' uses 'this' to access the object's own 'brand' property.
Understanding 'this' inside methods is crucial for writing object behaviors.
6
AdvancedPrototype chain and inheritance basics
🤔Before reading on: do you think properties on the prototype can be changed directly on the object? Commit to your answer.
Concept: Objects inherit properties from their prototype, forming a chain that JavaScript looks up when accessing properties.
const parent = { greet() { return 'Hello'; } }; const child = Object.create(parent); console.log(child.greet()); // Hello child.greet = function() { return 'Hi'; }; console.log(child.greet()); // Hi
Result
The child object first uses the parent's method but can override it by defining its own.
Knowing how the prototype chain works explains how inheritance and method overriding happen.
7
ExpertHidden internal slots and [[Prototype]] link
🤔Before reading on: do you think the prototype is a property you can see directly on the object? Commit to your answer.
Concept: Every object has an internal hidden link called [[Prototype]] that points to its prototype object, not accessible as a normal property.
JavaScript engines store a hidden [[Prototype]] link for each object. Accessing obj.__proto__ or Object.getPrototypeOf(obj) reveals this link. This link is used internally to find properties not on the object itself.
Result
Understanding that the prototype is a hidden internal link explains why some properties appear inherited but are not own properties.
Knowing about hidden internal slots clarifies many confusing behaviors around inheritance and property lookup.
Under the Hood
When you create an object, JavaScript sets up a hidden internal link called [[Prototype]] that points to another object. When you access a property, JavaScript first looks on the object itself. If it doesn't find it, it follows the [[Prototype]] link to look there, continuing up the chain until it finds the property or reaches the end. Constructor functions create new objects with their prototype set to the constructor's prototype property. Methods use 'this' to refer to the object that called them.
Why designed this way?
JavaScript was designed to be flexible and dynamic, allowing objects to share behavior without rigid class structures. The prototype system was chosen over classical inheritance to enable easy extension and reuse of objects. This design supports fast property lookup and dynamic changes, fitting JavaScript's role as a scripting language for the web.
Object Creation Mechanism
┌─────────────┐
│   Object    │
│  {props}    │
│ [[Prototype]]─────┐
└─────────────┘     │
                    ▼
             ┌─────────────┐
             │ Prototype   │
             │ {methods}   │
             └─────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does Object.create() copy properties or link prototypes? Commit to your answer.
Common Belief:Object.create() copies all properties from the given object to the new one.
Tap to reveal reality
Reality:Object.create() creates a new object with its prototype set to the given object; it does not copy properties.
Why it matters:Misunderstanding this leads to bugs where changes to the prototype affect all linked objects unexpectedly.
Quick: Does 'this' inside an object method always refer to the object itself? Commit to your answer.
Common Belief:'this' inside an object method always points to the object owning the method.
Tap to reveal reality
Reality:'this' depends on how the method is called, not where it is defined; it can point elsewhere or be undefined.
Why it matters:Assuming 'this' always points to the object causes errors when methods are extracted or called differently.
Quick: Are prototypes visible as normal properties on objects? Commit to your answer.
Common Belief:The prototype is a normal property you can see and change directly on the object.
Tap to reveal reality
Reality:The prototype is a hidden internal link, not a normal property; you access it via special means like Object.getPrototypeOf.
Why it matters:Confusing prototype with normal properties leads to incorrect code and misunderstanding of inheritance.
Quick: Does using 'new' with a constructor function always create a new object? Commit to your answer.
Common Belief:Using 'new' always creates a new object regardless of what the constructor returns.
Tap to reveal reality
Reality:If the constructor function returns an object explicitly, that object is returned instead of the new one.
Why it matters:Not knowing this can cause unexpected results and bugs when constructors return objects.
Expert Zone
1
Objects created with Object.create(null) have no prototype, making them ideal for pure key-value maps without inherited properties.
2
Modifying an object's prototype after creation is possible but can cause performance issues and is generally discouraged in production code.
3
Methods defined on prototypes are shared among all instances, saving memory compared to defining methods inside constructors.
When NOT to use
Avoid using constructor functions and prototypes directly when you need simpler syntax and better readability; instead, use ES6 classes. For pure data storage without inheritance, use Object.create(null) or Map objects. When performance is critical, avoid changing prototypes dynamically.
Production Patterns
In real-world JavaScript, objects are often created using ES6 classes which are syntactic sugar over prototypes. Factory functions are also popular for creating objects without 'new'. Prototypes are used to share methods efficiently. Immutable objects and object freezing are used to prevent accidental changes.
Connections
Class-based inheritance (OOP)
Builds-on
Understanding JavaScript's prototype-based object creation helps grasp how class syntax works under the hood, bridging classical and prototype inheritance.
Hash tables (Data Structures)
Same pattern
Objects in JavaScript behave like hash tables, mapping keys to values, which connects programming concepts to fundamental data structures.
Biological inheritance
Analogy to
Prototype chains in JavaScript resemble genetic inheritance where traits pass from parents to offspring, helping understand property lookup and overrides.
Common Pitfalls
#1Trying to copy an object by assigning it directly.
Wrong approach:const obj1 = {a: 1}; const obj2 = obj1; obj2.a = 2; console.log(obj1.a); // 2 (unexpected)
Correct approach:const obj1 = {a: 1}; const obj2 = Object.assign({}, obj1); obj2.a = 2; console.log(obj1.a); // 1 (correct)
Root cause:Assigning an object variable copies the reference, not the object itself, causing shared changes.
#2Calling a constructor function without 'new'.
Wrong approach:function Person(name) { this.name = name; } const p = Person('Alice'); console.log(p); // undefined console.log(name); // 'Alice' (pollutes global scope)
Correct approach:function Person(name) { this.name = name; } const p = new Person('Alice'); console.log(p.name); // Alice
Root cause:Without 'new', 'this' refers to the global object or undefined in strict mode, causing bugs.
#3Modifying the prototype of an object instance instead of the constructor's prototype.
Wrong approach:function Person() {} const p = new Person(); p.__proto__.greet = function() { return 'Hi'; }; const p2 = new Person(); console.log(p2.greet()); // Error
Correct approach:function Person() {} Person.prototype.greet = function() { return 'Hi'; }; const p = new Person(); const p2 = new Person(); console.log(p2.greet()); // Hi
Root cause:Adding methods to an instance's prototype affects only that instance, not all objects created by the constructor.
Key Takeaways
Objects in JavaScript are containers for related data and behavior, created using various methods like literals, constructors, or Object.create.
The prototype system allows objects to inherit properties and methods, enabling code reuse and dynamic behavior.
'this' inside object methods refers to the calling object, but its value depends on how the method is called.
Understanding the hidden [[Prototype]] link clarifies how JavaScript looks up properties and supports inheritance.
Common mistakes include confusing references with copies, forgetting 'new' with constructors, and misunderstanding prototype chains.