Check if Object Instance of Class - Leetcode 2618 - JavaScript 30-Day Challenge
Key Takeaways
The video discusses solving Leetcode 2618 using JavaScript, focusing on prototype chains and the instanceof operator to check if an object is an instance of a class. It covers JavaScript fundamentals, prototype inheritance, and object-oriented programming concepts.
Full Transcript
hey everyone welcome back and let's write some more neat code today I'll solve the problem check if object instance of a class we're given a function that takes two parameters and we want to implement that function and it's going to take one parameter as some object or maybe primitive value and a second parameter which is a class function which in this case like date is a class function and in JavaScript class functions are usually functions like this so for example if I wanted to create a class function person like this and it takes in a name then it's a class function if I use the this keyword to declare some variable like this now if I want to call person it's not going to work just by calling it like this I have to call it with the new keyword that's what makes this a class function and of course if I pass in a name then this will basically work just like a Constructor in most languages and it'll instantiate some object for us now why is that important because we're kind of checking types in this this case so taking a look at this example over here if we're given a date object that we just constructed and we want to know if it's an instance of the date class essentially the answer of course is going to be true now how exactly can we determine that well we're going to need to use some built-in JavaScript methods and functions that you probably haven't used before because they don't really come up super often now it might not be so straightforward suppose this example over here which I'm going to go ahead and copy and paste onto the right over here so in this case we are creating a animal class and creating a dog class which extends from the animal class and then we're checking is a dog an instance of the animal class well not directly but via inheritance it is because dog of course inherits from animal and this is of course using class syntax and JavaScript there's a lot of different ways to rewrite the same code that's what I hate about JavaScript but in this case the answer would also be true so that's something we're going to have to implement as well now you might be thinking how are we going to handle Primitives Primitives actually do have a prototype chain and that's kind of what we're doing here because in JavaScript there isn't the typical inheritance that you might be used to in like Java or C plus plus which I'm also used to JavaScript has a more lightweight implementation called prototype inheritance and in our case numbers are a part of the Prototype chain and in our case numbers have a prototype as well and that's kind of obvious because when you use like strings and numbers you can call methods on them like for a here I can create a string and then I can print the length of that string and this length field isn't just coming from nowhere it's coming from the Prototype chain the string prototype there are some differences though between creating a string like this and creating a string like this and I'll talk about that in just a second after our first solution but I think that's enough for us now now to get into this solution and we are going to need a few built-in methods so first of all maybe we can just check that the object is invalid like it's a falsy value and if that's the case it probably doesn't have any type of prototype and then we can just return false well not quite because like we just talked about we could be given a zero value we could be given an empty string and I believe those are also falsy but we wouldn't want to return false in that case because it's possible that they do have the matching class so let's be a bit more explicit and let's check if the object is not or is equal to null or the other one is the object is equal to undefined and in that case we return false and there is another Edge case which I think is kind of dumb the class function itself could also be a falsy value it could also be undefined it could be null but in our case we definitely want it to always be a class function so at the very least let's check that the type of the class function one is at least a function and I think we actually never talked about this type of we talked about all the Primitives we talked about objects but actually functions have a type as well which makes sense because it definitely should be distinct from an object so like this down here when we created this function its type would be function now how do we actually check the Prototype of an object because we want to make sure that the Prototype of this object matches this one well we can get the Prototype like this object dot get prototype of this given object so if I called this on a string it would return the Prototype string if I called it on number it would return the Prototype number and at this point you might think that we can just do a very simple comparison current prototype is equal to the class function dot prototype now first of all why are we just using the a DOT prototype attribute here whereas we had to call this function on the object well typically the Prototype field is hidden on the object if we try to do dot prototype we would probably get an error because that field is hidden so we can't just usually do it like that it's not that simple because we're in JavaScript land but why can we call Dot prototype on the class function well well that's the class itself and it should have access to its own prototype and don't worry I'll kind of do a quick demo towards the end to actually prove to you that that's what's going on but if this is true if this equality is true then we should probably just return true but if it's not true then should we return false well remember that last example down here we know that their prototype of a dog is going to be dog it's not going to be animal so how do we go down that prototype chain or go up the inheritance chain well we can do that with a loop So eventually the base case is going to be that the current prototype is going to be equal to null so while it's not equal to null we're basically going to be doing this operation and I'm going to go ahead and move that and I might as well just copy and paste this inside of the loop as well I guess we're redeclaring a variable every time but oh well actually now that I think of it we probably should move it on the outside because we don't want to call the Prototype method on object every single time but if this doesn't execute then let's do the same exact operation down here except instead of calling that on the object we're going to call it on the current prototype and eventually we'll either return true or out here we're going to return false and I also realized up here we had a slight bug we want to check we only want to return false if that's not a function so sorry about that and there goes our syntax highlighting but that is believe it or not the entire code I'm personally not satisfied though I don't feel like I entirely understand what's going on here so I am going to go deeper into the explanation but first let's run this code to make make sure that it works and as you can see yes it does and it's pretty efficient but now back to the drawing board now for that thing I was talking about at the end we have the date class and if we try to print the Prototype of that it's going to work but if we have a date object the Prototype is going to be hidden from it so if we try this right now you can see yeah that's pretty much exactly what's going on but then if we sort of change this part to actually say object dot get prototype of this instance and then we print it well now it works because again that's hidden from objects now this itself is a little bit misleading this kind of just makes it look like an empty object that's because we're doing this in node.js but now if I take this same code and let's just take this first line and I run it inside of my browser in the console tab here we can see printing that we get some big object and that object is the Prototype and you can see it has all the methods we'd expect from the date class it has get day get hours all that stuff as a Constructor so that's what we're doing here and now if I make a class suppose and I call it date subclass and I say it extends from the date class and then I try to construct an instance of this so if I say date well it says data sorry about that sub class and then I create an instance of this I'll call it D2 and now if I try to actually print the Prototype chain of D2 and I I do it with like the appropriate object get prototype and I pass in D2 over here let's see what happens let's run the code and you can see we get their prototype date subclass but if I call now on this I call get prototype of again on the outside of that what are we gonna get well let's make it a little bit more clear I'm going to get rid of this and I'm going to say here D2 Proto for short and then on the date subclass I'm going to call grit a get prototype on that so get prototype on D2 Roto closing parentheses and then running that then we get date we had to call it twice that's us going up the Prototype chain now if I call it one more time let's see what happens I'm running out of names and I've always been bad at naming things so I'm just calling that D2 Proto Proto and now I'm gonna call get prototype on that okay my brain isn't working today let's get prototype of okay let's rerun that and now you see we get pretty much empty so at that point we would pretty much terminate so that's most of what I wanted to show you and lastly I think it's definitely worth mentioning that what we pretty much implemented here today was the instance of operation except we kind of implemented it actually better than how it's implemented in JavaScript because look N1 is instance of a number what this is going to do is not what you might expect actually it's going to give us false but if I create a new number N2 and I I create it with the number Constructor and then I call instance of on that we do end up getting true because even though this number does have access to all the methods from the number class because it does go up their prototype chain it's not technically an instance of number because it wasn't created with a number Constructor and that's just because JavaScript is weird it allows us to use the methods even though it's technically not an instance of this and that's even more obvious when you do it with a string so I'm going to quickly copy and paste a bit of code here you can see a string declared with some quotes and then a string with a Constructor and this will also do the same thing we get false with this one and true with this one even though this string we can still log the length of it I can I can still say log S1 dot length and I can call a bunch of methods on it I can trim it I can get the slice maybe of it or a substring and that's because of course just because you declare a string like this doesn't mean you don't want access to all that functionality but when it comes to actually checking if it's an instance of it technically JavaScript tells us no it's not but still for both of these Primitives if we get the Prototype chain of both of them like this we do get the same thing they're both from the string prototype and that's why we used this to solve this problem we used get prototype of instead of using instance of because this doesn't completely solve the problem for us and very quickly just to prove it to you I'm going to run in the console tab console.log object dot get prototype of some empty string like that and when you run it you can see we do get the Prototype chain of string and all the methods like character at font size link all that stuff so if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io it has a ton of free resources to help you prepare thanks for watching and I'll see you soon
Original Description
Solving Day 25 of the Leetcode 30-day javascript challenge. Today we learn a lot about prototype chains in javascript, which is an alternative to class-based inheritance.
🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews
🥷 Discord: https://discord.gg/ddjKRXPqtk
🐦 Twitter: https://twitter.com/neetcode1
🐮 Support the channel: https://www.patreon.com/NEETcode
⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf
💡 DYNAMIC PROGRAMMING PLAYLIST: https://www.youtube.com/watch?v=73r3KWiEvyk&list=PLot-Xpze53lcvx_tjrr_m2lgD2NsRHlNO&index=1
Problem Link: https://leetcode.com/problems/check-if-object-instance-of-class/
0:00 - Read the examples
3:03 - Coding solution
7:03 - A Closer look at Prototype
leetcode 2618
#neetcode #leetcode #python
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from NeetCodeIO · NeetCodeIO · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
Design Linked List - Leetcode 707 - Python
NeetCodeIO
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
LFU Cache - Leetcode 460 - Python
NeetCodeIO
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
IPO - Leetcode 502 - Python
NeetCodeIO
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
Sort an Array - Leetcode 912 - Python
NeetCodeIO
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO
More on: LLM Foundations
View skill →Related Reads
📰
📰
📰
📰
Traversal, Linear Search, Swapping, Shifting & More (Leetcode Code example)
Medium · Data Science
The Rain Knows the Shortest Path
Medium · Programming
Data Structures & Algorithms for Mobile App Developers
Medium · Programming
Data Structures and Algorithms Deep‑Dive — Real-world Applications of Hash Tables (Chapter 3…
Medium · Programming
Chapters (3)
Read the examples
3:03
Coding solution
7:03
A Closer look at Prototype
🎓
Tutor Explanation
DeepCamp AI