CrackFrontendCF
Resources
Practice
CrackFrontend

Your guide to mastering frontend interviews

Resources

LibraryPracticeDonate

Company

About UsContact

Legal

Privacy PolicyTerms of Service

Built with ❀️ by Tushar Khanna

CrackFrontendCF
Resources
Practice

πŸ—οΈ Constructor Functions in JavaScript

Constructor functions create and initialize objects with shared properties and methods. Foundation for object-oriented patterns before ES6 classes.

A constructor in JavaScript is a special function used to create and initialize objects. It allows you to define reusable object structures. -- 1️⃣ What is a Constructor? A constructor function : Is a regular function but used with the keyword. Initializes an object and assigns properties to it. Typically follows PascalCase naming convention (, , ). Example of a Constructor Function πŸ“Œ How it works: 1. creates a new empty object . 2. inside refers to the newly created object. 3. The function assigns properties ( and ) to . 4. The new object is returned automatically. -- 2️⃣ Constructor Without (Why is Needed) If you forget to use , refers to the global object ( in browsers, in Node.js). βœ… Always use when calling a constructor function. -- 3️⃣ Constructor with Methods You can add methods inside the constructor, but it's inefficient because each instance gets a new copy of the method. -- 4️⃣ Constructor Prototype (Efficient Approach) Instead of defining methods inside the constructor, use prototype to share methods among all instances. πŸ“Œ Why use prototype? Reduces memory usage by sharing methods among instances. -- 5️⃣ Constructor in ES6 Classes (Modern Approach) ES6 introduces syntax, making constructor-based object creation cleaner. βœ… Same behavior as constructor functions but more readable. βœ… Uses prototype under the hood. -- 6️⃣ Checking Constructor Reference Each object instance retains a reference to its constructor. This is why resetting in prototype inheritance is necessary: -- 7️⃣ Custom Object Creation Without You can simulate by manually creating and returning an object. πŸ“Œ Difference? is not required. Object literals are used instead of . -- πŸš€ Summary Constructor Function Function-based keyword Inside function (bad) or prototype (good) Prototype-based (efficient) βœ… Use ES6 classes for cleaner, modern syntax. βœ… Use prototype for shared methods to improve performance. -- <!-quiz-start --Q1: What happens if you call a constructor function without the keyword? [ ] It throws a syntax error [x] refers to the global object (or undefined in strict mode) [ ] It automatically creates a new object [ ] The function returns null Q2: Why is it better to define methods on the prototype instead of inside the constructor? [ ] Methods on the prototype are faster to execute [ ] It's required by JavaScript specification [x] Methods on the prototype are shared among all instances, saving memory [ ] Methods inside the constructor don't work properly Q3: What does the property of an object instance reference? [ ] The prototype object [x] The function that created the instance [ ] The parent class [ ] The global object <!-quiz-end --
JavaScriptCore Concepts
πŸ›‘ AbortController: Canceling Async Operations in JavaScript
medium
πŸ”’ Closures in JavaScript β€” The Complete Guide
hard
πŸ“¦ Understanding ES6 Modules in JavaScript
medium
⚑ JavaScript Event Loop: Complete Guide to Asynchronous Execution
hard
🧭 Arrow Functions vs Function Declarations in JavaScript
easy
πŸ—‘οΈ Garbage Collection in JavaScript β€” Memory Management & Leak Prevention
hard
πŸ—οΈ Constructor Functions in JavaScript
medium
πŸ‘οΈ MutationObserver: Watching DOM Changes in JavaScript
medium
πŸ” Understanding `of` in JavaScript – `for...of` Loop Deep Dive
hard
πŸ”— Prototype and Prototype Inheritance in JavaScript
medium
πŸ•΅οΈ What Are Proxies in JavaScript? (With Practical Use Cases)
medium
🎯 Scope in JavaScript β€” The Complete Guide
hard
πŸ”„ Script Loading: async vs defer vs Both
hard
πŸ“€ JavaScript Spread Operator (...) Explained
easy
🎯 The JavaScript `this` Keyword: Complete Guide to Context Binding
medium
7 of 15
LibraryJavaScriptCore Concepts7 of 61

πŸ—οΈ Constructor Functions in JavaScript

jsgeneral-conceptsmedium

A constructor in JavaScript is a special function used to create and initialize objects. It allows you to define reusable object structures.


1️⃣ What is a Constructor?

A constructor function :

  • Is a regular function but used with the new keyword.
  • Initializes an object and assigns properties to it.
  • Typically follows PascalCase naming convention (Person, Car, Employee).

Example of a Constructor Function

function Person(name, age) {
  this.name = name;
  this.age = age;
}

const person1 = new Person("Alice", 25);
console.log(person1); // { name: "Alice", age: 25 }

πŸ“Œ How it works:

  1. new Person("Alice", 25) creates a new empty object .
  2. this inside Person refers to the newly created object.
  3. The function assigns properties (name and age) to this.
  4. The new object is returned automatically.

2️⃣ Constructor Without new (Why new is Needed)

If you forget to use new, this refers to the global object (window in browsers, global in Node.js).

const person2 = Person("Bob", 30); // No `new` used
console.log(person2); // ❌ undefined
console.log(window.name); // ❌ "Bob" (property assigned to global scope)

βœ… Always use new when calling a constructor function.


3️⃣ Constructor with Methods

You can add methods inside the constructor, but it's inefficient because each instance gets a new copy of the method.

function Car(brand, model) {
  this.brand = brand;
  this.model = model;
  this.displayInfo = function () {
    console.log(`Car: ${this.brand} ${this.model}`);
  };
}

const car1 = new Car("Toyota", "Camry");
const car2 = new Car("Honda", "Civic");

console.log(car1.displayInfo === car2.displayInfo); // ❌ false (new function created for each instance)

4️⃣ Constructor + Prototype (Efficient Approach)

Instead of defining methods inside the constructor, use prototype to share methods among all instances.

function Car(brand, model) {
  this.brand = brand;
  this.model = model;
}

// Add method to prototype (shared among all instances)
Car.prototype.displayInfo = function () {
  console.log(`Car: ${this.brand} ${this.model}`);
};

const car1 = new Car("Toyota", "Camry");
const car2 = new Car("Honda", "Civic");

console.log(car1.displayInfo === car2.displayInfo); // βœ… true (shared method)

πŸ“Œ Why use prototype?

  • Reduces memory usage by sharing methods among instances.

5️⃣ Constructor in ES6 Classes (Modern Approach)

ES6 introduces class syntax, making constructor-based object creation cleaner.

class Animal {
  constructor(name, type) {
    this.name = name;
    this.type = type;
  }

  speak() {
    console.log(`${this.name} says hello!`);
  }
}

const dog = new Animal("Buddy", "Dog");
dog.speak(); // Output: Buddy says hello!

βœ… Same behavior as constructor functions but more readable.

βœ… Uses prototype under the hood.


6️⃣ Checking Constructor Reference

Each object instance retains a reference to its constructor.

console.log(car1.constructor === Car); // βœ… true
console.log(dog.constructor === Animal); // βœ… true

This is why resetting constructor in prototype inheritance is necessary:

Employee.prototype.constructor = Employee;

7️⃣ Custom Object Creation Without new

You can simulate new by manually creating and returning an object.

function createPerson(name, age) {
  return {
    name,
    age,
    greet() {
      console.log(`Hi, I'm ${this.name}`);
    },
  };
}

const p1 = createPerson("Alice", 25);
p1.greet();

πŸ“Œ Difference?

  • new is not required.
  • Object literals are used instead of this.

πŸš€ Summary

FeatureConstructor FunctionES6 Class
SyntaxFunction-basedclasskeyword
Instantiationnewkeywordnewkeyword
Method DefinitionInside function (bad) or prototype (good)Inside class body
PerformancePrototype-based (efficient)Prototype-based (efficient)

βœ… Use ES6 classes for cleaner, modern syntax.

βœ… Use prototype for shared methods to improve performance.


Quick Quiz

Test your understanding with 3 quick questions

Q1What happens if you call a constructor function without the `new` keyword?
Q2Why is it better to define methods on the prototype instead of inside the constructor?
Q3What does the `constructor` property of an object instance reference?

Continue Reading

CrackFrontend

Your guide to mastering frontend interviews

Resources

LibraryPracticeDonate

Company

About UsContact

Legal

Privacy PolicyTerms of Service

Built with ❀️ by Tushar Khanna