JS Equivalent to Python isinstance()
Last Updated :
27 Dec, 2024
In Python, the isinstance() function is used to check if an object is an instance of a specific class or a subclass thereof. It’s an essential part of object-oriented programming in Python and helps ensure that the object is of the desired type before performing certain operations. In this article, we’ll explore how the Python isinstance() function works and how we can replicate similar behavior in JavaScript.
Syntax of isinstance()
isinstance(object, classinfo)
- object: The object whose type you want to check.
- classinfo: The class, type, or a tuple of classes that you want to compare the object's type against.
Example: Using isinstance() in Python
Python
class Animal:
pass
class Dog(Animal):
pass
dog = Dog()
print(isinstance(dog, Dog))
print(isinstance(dog, Animal))
print(isinstance(dog, object))
print(isinstance(dog, str))
OutputTrue
True
True
False
Explanation:
- isinstance(dog, Dog) returns True because dog is an instance of the Dog class.
- isinstance(dog, Animal) returns True because Dog is a subclass of Animal.
- isinstance(dog, object) returns True because all Python classes inherit from the object class.
- isinstance(dog, str) returns False because dog is not an instance of str.
JavaScript Equivalents to isinstance()
While JavaScript doesn’t have a direct equivalent to isinstance(), we can replicate similar functionality using instanceof, typeof and custom checks for built-in objects. These methods provide ways to check an object’s type or class.
Using instanceof Operator
In JavaScript, the instanceof operator checks whether an object is an instance of a specific class or constructor function.
Example: Using instanceof in JavaScript
JavaScript
class Animal {}
class Dog extends Animal {}
const dog = new Dog();
console.log(dog instanceof Dog);
console.log(dog instanceof Animal);
console.log(dog instanceof Object);
console.log(dog instanceof String);
Outputtrue
true
true
false
Explanation:
- dog instanceof Dog returns true because dog is an instance of the Dog class.
- dog instanceof Animal returns true because Dog is a subclass of Animal.
- dog instanceof Object returns true because all JavaScript objects inherit from Object.
- dog instanceof String returns false because dog is not an instance of String.
Using typeof Operator
While typeof is not directly comparable to isinstance(), it can be used to check if a value is of a certain primitive type such as string, number, boolean, etc.
Example: Using typeof in JavaScript
JavaScript
const num = 10;
const str = "Hello, Shivang";
console.log(typeof num === 'number');
console.log(typeof str === 'string');
console.log(typeof num === 'string');
console.log(typeof str === 'object');
Outputtrue
true
false
false
Explanation:
- typeof num === 'number' returns true because num is of type number.
- typeof str === 'string' returns true because str is of type string.
- typeof num === 'string' returns false because num is not of type string.
- typeof str === 'object' returns false because str is not of type object.
Note: typeof is typically used for primitive types but won't work for checking classes or constructor functions.
Using constructor Property
We can also check the constructor property of an object to determine its class. This method is useful if we're checking custom objects.
Example: Using constructor Property in JavaScript
JavaScript
class Animal {}
class Dog extends Animal {}
const dog = new Dog();
console.log(dog.constructor === Dog);
console.log(dog.constructor === Animal);
console.log(dog.constructor === Object);
Explanation:
- dog.constructor === Dog returns true because dog was created by the Dog constructor.
- dog.constructor === Animal returns false because the constructor of dog is Dog, not Animal.
- dog.constructor === Object returns false because dog is not an instance of Object, it is an instance of Dog.
Custom Type Checks (For Non-Class Objects)
For non-class objects (like arrays, date objects, etc.), JavaScript provides specialized methods to check types.
Example: Checking for Arrays and Dates
JavaScript
const arr = [1, 2, 3];
const date = new Date();
console.log(Array.isArray(arr));
console.log(arr instanceof Array);
console.log(date instanceof Date);
console.log(date instanceof Object);
Outputtrue
true
true
true
Explanation:
- Array.isArray(arr) checks if arr is an array.
- arr instanceof Array also checks if arr is an instance of Array.
- date instanceof Date checks if date is an instance of Date.
Similar Reads
Js Equivalent to Python In In Python, it is used for iterating over elements, checking membership and even used for conditional checks. JavaScript offers similar functionality with different syntax and behavior. This article discusses how Python's in keyword works in different contexts and how to achieve similar behavior in J
3 min read
JS Equivalent to Python Get In Python, the get() method is often used with dictionaries to retrieve values associated with a given key, while providing a default value if the key does not exist. JavaScript, however, does not have a built-in get() method for objects. In this article, we will explore different methods to replica
3 min read
type and isinstance in Python In this article, we will cover about type() and isinstance() function in Python, and what are the differences between type() and isinstance(). What is type in Python? Python has a built-in method called type which generally comes in handy while figuring out the type of the variable used in the progr
5 min read
isinstance() method - Python isinstance() is a built-in Python function that checks whether an object or variable is an instance of a specified type or class (or a tuple of classes), returning True if it matches and False otherwise, making it useful for type-checking and ensuring safe operations in dynamic code. Example:Pythonx
3 min read
isinstance() method - Python isinstance() is a built-in Python function that checks whether an object or variable is an instance of a specified type or class (or a tuple of classes), returning True if it matches and False otherwise, making it useful for type-checking and ensuring safe operations in dynamic code. Example:Pythonx
3 min read
numpy.isfinite() in Python The numpy.isfinite() function tests element-wise whether it is finite or not(not infinity or not Not a Number) and return the result as a boolean array. Syntax :Â numpy.isfinite(array [, out]) Parameters :Â array : [array_like]Input array or object whose elements, we need to test for infinity out :
2 min read