Lesson 32: Mastering JavaScript Constructor Functions and the new Operator with challenges!

manoj ymkmanoj ymk
4 min read

A constructor function in JavaScript is used to create multiple instances of similar objects. When invoked with the new operator, the function:

  1. Creates a new empty object.

  2. Sets this to point to that object.

  3. Executes the function body.

  4. Returns the object this (unless it returns another object explicitly).

โœ… Syntax

function User(name) {
  this.name = name;
  this.isAdmin = false;
}

let user1 = new User("Alice");
let user2 = new User("Bob");

Both user1 and user2 now have the same structure but different values.

๐Ÿ” Visual Flowchart

new User("Alice") โžก
    Step 1: Create empty object โ†’ {}
    Step 2: Set `this` to the new object
    Step 3: Execute User function โ†’ this.name = "Alice"
    Step 4: Return the object โ†’ { name: "Alice", isAdmin: false }

Real-World Example

function Product(name, price) {
  this.name = name;
  this.price = price;
  this.discount = function(percent) {
    return this.price * (1 - percent / 100);
  };
}

let phone = new Product("iPhone", 1200);
console.log(phone.discount(10)); // 1080

๐Ÿ”น 2. Fill Any Gaps

๐Ÿ”ธ Common Misconceptions

  • Arrow functions cannot be used as constructors (TypeError: Class constructor can't be invoked without 'new')

  • Forgetting new leads to this pointing to window or undefined in strict mode.

  • Returning an object overrides the default this.

๐Ÿ”ธ Edge Cases

function Person(name) {
  this.name = name;
  return { custom: "object" }; // overrides the `this` return
}
let p = new Person("Tom");
console.log(p.name); // undefined
console.log(p.custom); // object

๐Ÿ”ธ new.target

Helpful for ensuring a constructor is called properly:

function ForceNew(name) {
  if (!new.target) return new ForceNew(name);
  this.name = name;
}

๐Ÿ”ธ Performance Trap

Methods defined inside the constructor are recreated per instance, unlike prototypes:

function Car() {
  this.drive = function() {}; // bad for memory if many instances
}

๐Ÿ”น 3. Challenge Me Deeply

๐ŸŸข Basic

  1. Create a Book constructor with title and author.

  2. Make a Circle constructor that calculates area.

  3. Create a Dog constructor with bark() method.

๐ŸŸก Intermediate

  1. Add a prototype method to a constructor to reduce memory usage.

  2. Use new.target to enforce use of new.

  3. Write a constructor that returns a different object conditionally.

๐Ÿ”ด Advanced

  1. Create a singleton with a constructor.

  2. Simulate new behavior manually with a function.

  3. Create a Timer constructor that tracks elapsed time.

  4. Make a constructor chain (e.g., Admin extends User) without using classes.

๐ŸŽฏ Brain Twister

  1. Write a constructor that creates only one instance for any given name (a basic flyweight pattern).

๐Ÿ”น 4. Interview-Ready Questions

โœ… Conceptual

  • What does the new keyword do behind the scenes?

  • Can every function be a constructor?

โœ… Scenario-Based

  • You have a constructor that must behave correctly with and without new. How would you design it?

  • How would you make sure that methods aren't redefined for every instance?

โœ… Debugging

function Robot(name) {
  this.name = name;
  return "Not a robot";
}
let rob = new Robot("Wall-E");
console.log(rob.name); // ???

โœ… Best Practices

โœ… Use prototypes for methods
โœ… Name constructors with PascalCase
๐Ÿšซ Avoid redefining methods inside the constructor
๐Ÿšซ Donโ€™t forget new


๐Ÿ”น 5. Real-World Usage

  • DOM wrappers: Like new XMLHttpRequest()

  • Frameworks: React components before hooks were class-based (class extends React.Component)

  • Custom Error Types:

      function ValidationError(message) {
        this.message = message;
        this.name = "ValidationError";
      }
    

๐Ÿ”น 6. Remember Like a Pro

Mnemonic:

"NEW helps me create something NEW!"

Cheatsheet:

RuleResult
Constructor returns object?That object is returned
Constructor returns primitive?Ignored, this is returned
No return?this is returned
Arrow function?โŒ Not a constructor

๐Ÿ”น 7. Apply It in a Fun Way

๐Ÿงช Mini Project: TodoApp Constructor

1. Create a constructor `TodoApp(title)`
2. Add `addTodo()` and `listTodos()` methods
3. Store todos in an array
4. Display summary with total count

Bonus: Extend it!

  • Add a deleteTodo(id)

  • Save to localStorage

  • Add a simple UI (bonus project)


โž• Bonus Insights

๐Ÿงช Open-source Use

  • express.Router() โ†’ constructor behind the scenes

  • new Vue() in Vue 2

  • new Error() in almost every JS lib

โŒ Common Mistakes

  • Using arrow functions as constructors

  • Not using new

  • Attaching heavy logic inside constructor body

๐Ÿ› ๏ธ Performance Tips

  • Always attach shared methods to .prototype

  • Avoid returning objects unless you need to

0
Subscribe to my newsletter

Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

manoj ymk
manoj ymk