Bird
Raised Fist0
Javascriptprogramming~10 mins

Constructors in classes in Javascript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Constructors in classes
Create class with constructor
↓
Create new object with 'new'
↓
Call constructor method
↓
Initialize object properties
↓
Return new object
↓
Use object
When you create a new object from a class, the constructor runs first to set up the object's properties.
Execution Sample
Javascript
class Person {
  constructor(name) {
    this.name = name;
  }
}
const p = new Person('Anna');
console.log(p.name);
This code creates a Person object with a name property set by the constructor, then prints the name.
Execution Table
StepActionEvaluationResult
1Define class Person with constructorclass Person {...}Class Person ready
2Call new Person('Anna')Calls constructor with name='Anna'New Person object created
3Inside constructor: this.name = namethis.name = 'Anna'Object property name set to 'Anna'
4Constructor returnsImplicit return of new objectPerson object with name='Anna'
5console.log(p.name)Access p.nameOutput: Anna
💡 Constructor finishes after setting properties; object is ready to use.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
pundefinedPerson object (empty)Person object with name='Anna'Person object with name='Anna'
this.nameundefinedundefined'Anna''Anna'
Key Moments - 2 Insights
Why do we use 'this.name = name' inside the constructor?
Because 'this' refers to the new object being created, so 'this.name = name' sets the object's property. See execution_table step 3.
What happens if we forget to use 'new' when creating the object?
The constructor won't run properly and 'this' won't refer to a new object, causing errors or unexpected results. See execution_table step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'this.name' after step 3?
A'Anna'
Bundefined
Cnull
DError
💡 Hint
Check the 'Evaluation' and 'Result' columns in step 3 of the execution_table.
At which step does the constructor finish and the object is ready to use?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look for the step where the constructor returns the new object in the execution_table.
If we change 'new Person("Anna")' to 'new Person("Bob")', what changes in the variable_tracker?
Ap.name becomes 'Anna'
Bp.name becomes 'Bob'
Cp.name becomes undefined
DNo change
💡 Hint
Check how 'this.name' is set in the constructor and tracked in variable_tracker.
Concept Snapshot
class ClassName {
  constructor(params) {
    this.property = params;
  }
}

Use 'new ClassName(args)' to create an object.
Constructor runs first to set properties.
'this' refers to the new object.
Full Transcript
A constructor is a special method inside a class that runs automatically when you create a new object with 'new'. It sets up the object's properties using 'this'. In the example, the Person class has a constructor that takes a name and assigns it to 'this.name'. When we do 'new Person("Anna")', the constructor runs, sets the name property, and returns the new object. Then we can use the object and access its properties like 'p.name'.

Practice

(1/5)
1. What is the main purpose of a constructor in a JavaScript class?
easy
A. To create static properties for the class
B. To define methods that all objects share
C. To initialize new objects with default or given values
D. To delete objects when they are no longer needed

Solution

  1. Step 1: Understand the role of a constructor

    A constructor is a special method in a class that runs automatically when a new object is created.
  2. Step 2: Identify what constructors do

    Constructors set initial values for the object's properties using this.
  3. Final Answer:

    To initialize new objects with default or given values -> Option C
  4. Quick Check:

    Constructor = initialize object [OK]
Hint: Constructors always set up new objects [OK]
Common Mistakes:
  • Confusing constructors with regular methods
  • Thinking constructors delete objects
  • Believing constructors create static properties
2. Which of the following is the correct syntax to define a constructor inside a JavaScript class?
easy
A. constructor() { this.name = 'John'; }
B. function constructor() { this.name = 'John'; }
C. def constructor() { this.name = 'John'; }
D. constructor = () => { this.name = 'John'; }

Solution

  1. Step 1: Recall JavaScript class constructor syntax

    In JavaScript classes, the constructor is defined as a method named constructor without the function keyword.
  2. Step 2: Check each option

    constructor() { this.name = 'John'; } uses the correct syntax: constructor() { ... }. Options B and C incorrectly use keywords from other languages or function syntax. constructor = () => { this.name = 'John'; } uses arrow function syntax, which is invalid for constructors.
  3. Final Answer:

    constructor() { this.name = 'John'; } -> Option A
  4. Quick Check:

    Constructor method = constructor() { } [OK]
Hint: Constructor is a method named exactly 'constructor' [OK]
Common Mistakes:
  • Adding 'function' keyword before constructor
  • Using arrow functions for constructors
  • Using other language syntax like 'def'
3. What will be the output of the following code?
class Person {
  constructor(name) {
    this.name = name;
  }
  greet() {
    return `Hello, ${this.name}!`;
  }
}
const p = new Person('Alice');
console.log(p.greet());
medium
A. Hello, undefined!
B. Hello, Alice!
C. Hello, !
D. TypeError: p.greet is not a function

Solution

  1. Step 1: Understand object creation with constructor

    The Person class constructor sets this.name to the passed argument. Here, 'Alice' is passed, so p.name becomes 'Alice'.
  2. Step 2: Evaluate the greet method output

    The greet method returns a string using this.name, which is 'Alice'. So, p.greet() returns 'Hello, Alice!'.
  3. Final Answer:

    Hello, Alice! -> Option B
  4. Quick Check:

    Constructor sets name, greet uses it = Hello, Alice! [OK]
Hint: Constructor sets property, method uses it [OK]
Common Mistakes:
  • Forgetting to pass argument to constructor
  • Expecting undefined because of missing this
  • Thinking greet is not a method
4. Identify the error in this class definition:
class Car {
  constructor(make, model) {
    make = make;
    model = model;
  }
}
medium
A. Properties should be assigned using this, like this.make = make;
B. The class name should be lowercase
C. The constructor should not have parameters
D. The constructor must return an object explicitly

Solution

  1. Step 1: Review property assignment in constructor

    Inside a constructor, to assign values to the object's properties, you must use this.propertyName. Simply writing make = make; assigns the parameter to itself, which does nothing.
  2. Step 2: Identify the correct fix

    Using this.make = make; and this.model = model; correctly assigns the values to the new object's properties.
  3. Final Answer:

    Properties should be assigned using this, like this.make = make; -> Option A
  4. Quick Check:

    Use this.property = parameter [OK]
Hint: Always use this.property to assign inside constructor [OK]
Common Mistakes:
  • Assigning parameters to themselves
  • Not using this to set properties
  • Thinking constructor must return explicitly
5. You want to create a Book class where each book has a title and an optional author. If no author is given, it should default to 'Unknown'. Which constructor correctly implements this behavior?
hard
A. constructor(title, author) { this.title = title; if (author) this.author = author; }
B. constructor(title, author) { this.title = title; this.author = author || 'Unknown'; }
C. constructor(title) { this.title = title; this.author = 'Unknown'; }
D. constructor(title, author = 'Unknown') { this.title = title; this.author = author; }

Solution

  1. Step 1: Understand optional parameters in constructors

    Use default parameter values for optional arguments. constructor(title, author = 'Unknown') { this.title = title; this.author = author; }: constructor(title, author = 'Unknown') sets author to 'Unknown' if not provided or undefined, but keeps passed falsy values like empty string.
  2. Step 2: Check other options

    B uses ||, which defaults falsy values (not just missing). C has no author param. D sets only if truthy, else undefined.
  3. Final Answer:

    constructor(title, author = 'Unknown') { this.title = title; this.author = author; } -> Option D
  4. Quick Check:

    Optional param: param = default [OK]
Hint: Default params for optional constructor args [OK]
Common Mistakes:
  • Using logical OR (||) which treats falsy as missing
  • Omitting the optional parameter entirely
  • Not providing a default, leaving undefined
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard