How to get the Class name of an Object in JavaScript
Table of Contents
JavaScript supports object-oriented programming, which means that you can create classes and objects, and use them to store data.
One useful thing to be able to know from an object is the name of the class it was created from.
In this post, we'll learn how you can get the class name of an object in JavaScript.
Getting the class name of an object
First let's start with a class and an object created from it.
JAVASCRIPTclass Shape {}
const triangle = new Shape();
Given the object triangle
, we can get the class name of it using the constructor
property, which returns a reference to the constructor function that created the object, then using the name
property to get the name of the class.
JAVASCRIPTclass Shape {}
const triangle = new Shape();
console.log(triangle.constructor.name);
BASHShape
The reason this works is you can use the constructor
property to get the class of an object, which includes the name, along with other properties.
Because most things in JavaScript are objects, they will therefore have a valid constructor
property.
Conclusion
In this post, we'll learn how you can get the class name of an object in JavaScript by using the constructor
property.
This is useful because it allows you to get the name of the class that created an object, which can be useful for debugging.
Thanks for reading!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Getting Started with Express
- Create an RSS Reader in Node
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- How to deploy a MySQL Server using Docker
- Getting Started with Sass
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Using Axios to Pull Data from a REST API