Skip to main content

Command Palette

Search for a command to run...

Exploring the Power of new.target in JavaScript

Updated
โ€ข1 min read
R

I'm a technology enthusiast who does web development. Passionate to contribute to open-source projects and making cool products.

โœ” Iโ€™m currently learning about Flutter โœ” Ask me anything you want, If I'm alive I will answer within seconds ๐Ÿ˜‰ โœ” I Always try to learn something new & then sleep till it stores in the brain ๐Ÿ˜Ž

In JavaScript, the new.target property is a meta-property that can be used to determine whether a function was called with the new keyword. It returns a reference to the constructor function that was invoked with the new keyword or undefined if the function was not called with new.

function MyClass() {
  if (new.target) {
    console.log('MyClass was called with new');
  } else {
    console.log('MyClass was not called with new');
  }
}

new MyClass(); // MyClass was called with new

MyClass(); // MyClass was not called with new

new.target can be useful for implementing custom constructor functions, where you want to ensure that the function is always called with new, or for creating abstract base classes that cannot be instantiated directly.

function MyClass() {
  if (!new.target) {
    throw new Error('MyClass must be called with new');
  }
}
If you enjoyed reading this short blog, you may also want to check out my javascript short playlist on YouTube.
Must Read If you haven't

React best practices and patterns to reduce code - Part 1

React best practices and patterns to reduce code - Part 2

React.js state management using signals

useAsync hook with cache

More content at Hashnode.
Catch me on: Youtube, Github, Twitter, LinkedIn, Medium, Dev.to, Blogspot, Stackblitz