Home > Programming > Understanding typeof, instanceof and constructor in JavaScript

Understanding typeof, instanceof and constructor in JavaScript

September 18th, 2011

They say in JavaScript “everything is an object”. They’re wrong. Some types in JavaScript are so-called “primitive types”, and they don’t act like objects. These types are:

  • Undefined
  • Null
  • Boolean
  • Number
  • String

The confusion comes from the fact that the boolean, number and string types can be treated like objects in a limited way. For example, the expression "I'm no object".length returns the value 13. This happens because when you attempt to access properties or methods on a primitive value, JavaScript instantiates a wrapper object temporarily, just so you can access its methods. ‘Cause JavaScript’s nice like that. I’m not going to go into more details here, but Angus Croll wrote about The Secret Life of JavaScript Primitives, so that would be a good place to learn more.


typeof is a unary operator, just like the ! operator. It returns a string representing the type of its operand. Here are some examples:

typeof 3; // returns "number"
typeof 'blah'; //returns "string"
typeof {}; //returns "object"
typeof []; //returns "object"
typeof function () {}; //returns "function"

typeof has its idiosyncrasies. For example, typeof null returns "object", and typeof /[a-z]/ returns "function". Again, Angus Croll has written more on this subject than I have space for here.

So, basically typeof is used for telling apart the different primitive types (as long as you don’t care about null). It’s no use for telling different types of object apart though – for most objects typeof will return "object".


constructor is a property available on all objects’ prototypes, and it is a reference to the constructor function used to create the object. So, ({}).constructor returns the Object constructor function (the parentheses are needed to clarify a syntactic ambiguity) and [].constructor returns the Array constructor function. Likewise, it will return your custom constructor function:

function Person(name) {
  this.name = name;

var dave = new Person('Dave');
dave.constructor === Person; //true

Remember that unlike the typeof operator, constructor returns a reference to the actual function. Another gotcha: because constructor is part of the prototype, if you reassign the prototype to a constructor function, e.g. Person.prototype = {};, you’ll lose the constructor property.


instanceof is a binary operator – its syntax is instance instanceof Constructor. So, to continue the above example:

dave instanceof Person; //true

The difference between instanceof and the constructor property (apart from the obvious syntactic difference) is that instanceof inspects the object’s prototype chain. So, going back to our friend dave again:

dave instanceof Object; //true

This is because Person.prototype is an object, so Object is in dave‘s prototype chain, therefore dave is an instance of Object.


So, if you’re dealing with primitive objects, use typeof to distinguish them. Because typeof returns "function" for functions, it can also be useful for checking if an object member or a function argument is a function. If you’re working out the constructor of an object, use its constructor property. And if you’re dealing with lengthy inheritance chains, and you want to find out whether an object inherits from a certain constructor, use instanceof.

Categories: Programming Tags: ,
  1. September 19th, 2011 at 11:31 | #1

    A small clarification: .constructor is, I believe, a property of an object’s prototype, in the usual case. That is, accessing foo.constructor will, by default, fall back to asking foo’s [[Prototype]] about its .constructor.

  2. September 19th, 2011 at 11:41 | #2

    @Federico Lebrón You’re absolutely right, thanks. I’ve updated the post to clarify that.

  3. August 13th, 2012 at 19:30 | #3

    I found your article very useful while writing JavaScript Confusing Bits. Thanks a lot! Hope you don’t mind borrowed sentence explaining what is instanceof operator. Thanks a lot.

  4. Balpalumb
    October 26th, 2012 at 19:02 | #4

    Прелестный блог, делюсь с Вами, наслаждайтесь, изучайте, зарабатывайте, http://ochupella.ru/

  5. August 3rd, 2013 at 02:33 | #5

    Heya i am for the primary time here. I came across this board and I to find It truly useful & it helped me out a lot. I hope to provide something again and help others such as you helped me.

  6. October 15th, 2013 at 12:51 | #6

    I love foregathering utile information, this post includes me further info!

  7. October 26th, 2013 at 02:51 | #7

    ブレス ネックレス チャンルー アクセサリー http://www.manialounge.com/ブレスレット、バングル-zp8h9ev-4.html/

  8. November 14th, 2013 at 01:40 | #8

    もちろん、そのために優秀で有能な営業マンと優秀な品質が前提となることは敢えて言うまでもない。 ミニッツレーサーと同じく、トレッド幅(タイヤの換装により2種類選択可能)が合えば、改造によりプラモデルボディーも搭載可能ですので、オリジナルパームランナーも頑張れば夢ではありません→ミニッツレーサーとパームランナーの比較はこちら、他の室内RCとの比較スピード制御は有るものの、ミニッツレーサーは速過ぎて、正直言って手に余るものがありました。 いつしか菅谷のアパートに医師たちが集まり、勉強会が開かれるようになった。 午前3時ごろの現場では、軽乗用車が歩道に乗り上げ、前部バンパーの右側が約40センチ四方へこんでいた。 「英検王」の特徴 リスニング問題重視! ボリューム満点の約300問。 会場は、新世界特設会場(「スパワールド世界の大温泉」北側)ほか。 演歌歌手・前川清を主演に迎え、『ブタがいた教室』の前田哲が監督を務めたヒューマン・ドラマ。 その内容たるや、授業で出された“宿題”の解答を教えてくれというものだった〈今とっている授業の一つで、グローバルファッションマーチャンダイジングっていう授業があるの。 )前田智徳を神宮で見たときと、柔道軽量級の野村の投げを見たときぐらいですとも! こんなにドストエフスキーに悪意を抱いているのなら、ドストエフスキーについて論じる必要はないはずだ。50歳の若さで亡くなった山田さんをしのぶ会には、日大の同期だけにとどまらず、甲子園ボウルで「赤と青」の名勝負を繰り広げた関学大のOBからも故人を悼むメッセージが届いた。 |無料メール相談|インターネット事務所利用案内| 資格商法特集|これが電話勧誘の手口だ! ジバンシーは、その後、セリーヌ、クリスチャン·ディオール、ラクロワ、および多くのような他の有名なデザイナーと一緒に、 モエヘネシー(adidasMH)グループの一部になるように誘われた。 ノーマルシャフト(F75ーX)とは言え、TOUR ADの冠が付いた75gのXフレックスだけにオーバースペックではないかと一抹の不安があったが、なかなかの強弾道でこれも一安心。 彼らは深い複雑なデザインを持っているとzadosi、金属、金やsiadidaseスレッドの仕事の重い仕事で飾られています!

  9. April 7th, 2014 at 19:34 | #9

    The more you know what you happen to be looking for in terms of bathroom cabinets, the more you can make out of getting custom cabinets placed in your bathroom. When researching for contractors for cabinets, it is possible to refer to magazines, local newspapers plus websites. Practically everything about the kitchen involves a cabinet.

    Also visit my website; [Car Accident Lawyer Denver](https://www.youtube.com/watch?v=BlLn2urWPn0 “Car Accident Lawyer Denver”)

  10. July 11th, 2014 at 11:37 | #10

    Hola! I’ve been following your website for a long time now and finally got the courage to go ahead and give you a shout out from Dallas Tx! Just wanted to say keep up the good job!

  11. September 15th, 2014 at 01:58 | #11

    Dans la couche d’accès aux données, si nous utilisons Entity Framework, LINQ to SQL ou Hibernate, nous utilisons souvent l’interface IQueryable, spécifiant ce que Abalorio Pandora Contra El Cancer nous voulons interroger avant que le moteur ou / M se traduit cela en SQL et renvoie des données. Comme la température du corps tombe, étape 3, la transpiration, commence, provoquant des sentiments de fatigue extrême et de la faiblesse. La version 4.5 est Tamagotchi l

  12. September 20th, 2014 at 10:46 | #12

    I like what you guys are usually up too. Such clever work and exposure! Keep up the great works guys I’ve incorporated you guys to blogroll.

    My site; [pest control companies in michigan](http://www.meilidianfeng.com/space.php?uid=121143&do=blog&id=252041 “pest control companies in michigan”)

  13. September 22nd, 2014 at 07:37 | #13

    Knowing how to promote your online business helps to make the difference between no sales or occasional sales and significant online income. While nearly you can now come up with great ideas for websites or other pages, anyone who has tried online marketing knows all too well how difficult it may be to make your first sale. So what exactly is going to Air max work for you? Lets explore how you can promote your online business on today’s internet landscape.But it is still useful.Most software eng

  14. September 24th, 2014 at 10:56 | #14

    Betekent banen gedurende [bouwmaterieel's] de en het betekent werkgelegenheid voor Woolrich Nederland de lange termijn, zei Arnold. we zijn, we zijn erg gewend aan het werken met energieproducenten. Dit is een grote volgende stap voor ons. Volgens Jassen Moncler Outlet de overeenkomst, Greenfield Zuid macht krijgt om de kostbare grond net ten noordwesten van Sherway plus $ 85.000.000 voor bouwmaterialen, arbeid, engineering, vergunningen en andere kosten te houden. Als je slecht beoordelingsverm

  15. October 5th, 2014 at 07:46 | #15

    Hi friends, how is the whole thing, and what you wish for to say on the topic of this piece of writing, in my view its genuinely awesome designed for me.

  16. October 13th, 2014 at 02:11 | #16

    Il s’agit d’un livre accessible wellwritten sur la façon de perdre du poids ou comment avoir juste une alimentation saine sans recourir au comptage de calories obsessionnelle ou régimes miracles étranges qui interdisent groupes alimentaires entiers (je sais Atkins travaille pour les gens, mais il me remplit de toutes sortes . Cela ouvre également la société à des problèmes si les prix commencent à tomber. Les spécialistes du cancer: l’allaitement

  17. October 21st, 2014 at 00:40 | #17

    I believe that is among the most significant information for me. And i’m glad reading your article. However wanna remark on some common things, The web site style is perfect, the articles is actually excellent : D. Good job, cheers

  18. December 15th, 2014 at 15:08 | #18

    I got this website from my friend who shared with me regarding this web site and now this time I am visiting this web page and reading very informative content here.

    My site – [apple iphone 5 unlocked](http://getunlockediphone.com/ “apple iphone 5 unlocked”)

  19. January 21st, 2015 at 14:16 | #19

    thank youu :))

  20. January 22nd, 2015 at 01:08 | #20

    Kleine Dinge wie ineinander greif unseren Schreibtischen mit unserer Laufbänder sorgen für Stabilität helfen, die Begrenzung der maximalen Geschwindigkeit auf dem Laufband zu 4 MPH (die maximale Geschwindigkeit kann der Benutzer bis zu 2 MPH wenn gewünscht FAQ angepasst sein), und Stanzlifespan auf dem Band zu Band Bewegung zeigen werden . Warten zu kassieren, bis Sie in Rente gehen, sparen Sie noch mehr, weil Ihr Einkommen wird wahrscheinlich niedriger sein, wenn Sie nicht m

  21. February 12th, 2015 at 12:15 | #21

    well, thank you :))

  22. March 30th, 2015 at 22:04 | #22

    If it’s encoded on the tag, they won’t’ have to commit the URL to memory.

    Remember that the discount should work as bait without gobbling up your income. If you are a small or medium scale business and you want to reach out to people at trade shows, printed pens are one of the best promotional products to do so on a budget.

  23. April 9th, 2015 at 11:56 | #23

    Loving information on this web site , you have done a great job articles.

  24. April 22nd, 2015 at 08:30 | #24

    nice topic.thanks

  25. May 2nd, 2015 at 23:10 | #25

    They can focus for longer periods of time, so you may use fewer activities in your sessions. t help at all to enter into argument or disagreeing with the referee. With some transfer deals or with an affiliate club (a club in a relationship with your own that is there to supply loan players and the like) a friendly match might be a result of the agreement, so it is worth making the most of these games and play your best team where possible.

  26. May 29th, 2015 at 00:54 | #26

    For one thing, these units are completely eco-friendly, relying on nothing more than the power of super-heated steam to loosen and remove different kinds of stains and deposits.

    What is the most ideal lightweight carpet vacuum cleaner. Of course, because a vacuum appliance is very important in our lives, we must do all we can to make sure that service continues for a longer period of time.

  27. June 6th, 2015 at 18:56 | #27

    It includes a wide range of exercises that you can perform right in the convenience of your home. So to get crystal clear audio, it’s just not going to happen. If you haven’t even bought your kids play equipment yet, then always look for a manufacturer who supplies foam protection as standard.

  28. June 11th, 2015 at 11:28 | #28

    If the glove gets messy, you can wash the glove in cold water with a mild laundry detergent. It has up to 99 minute long grilling time for preparation of a variety food items. Before purchasing any appliance for your home, you must read reviews from users and experts given on the online shopping portals.

  29. June 16th, 2015 at 02:40 | #29

    Ideas which can do justice to the emotions associated with every event. It can be played during the celebrant’s party and even after some days or years after. To learn more about gift ideas, visit our website at My – Reviews – Now.

  30. June 18th, 2015 at 15:53 | #30

    thanks admin nice post shared

  31. June 18th, 2015 at 16:34 | #31

    thanks admin nicccce

  32. July 9th, 2015 at 10:14 | #32

    Thanks for the information..

  33. August 10th, 2015 at 12:38 | #33

    Awesome! Its actually remarkable post, I have got much clear idea concerning from this piece of writing.

  34. August 13th, 2015 at 20:46 | #34

    Some corporations giving server supervision present Spam safety and antivirus installations to make sure consistency of the machine.

  35. August 16th, 2015 at 22:59 | #35

    Very good information. Lucky me I recently found your site by accident (stumbleupon). I’ve bookmarked it for later!

  36. September 12th, 2015 at 16:55 | #36

    thanks admin nice post shared

  37. October 16th, 2015 at 14:26 | #37

    Its actually remarkable post, I have got much clear idea concerning from this piece of writing. thanks

  38. November 8th, 2015 at 01:25 | #38
    • Flexibility Lastly, find a financing method which provides flexibility when it comes to paying your loans. As discussed earlier, one of the most important is Attractively-low Interest rates which only an online Bad credit car financing can offer due to its various tie-ups with numerous lenders. It is because having your own car is most likely more beneficial to you in so many ways than not having one.

    My site webpage ([Viola](http://test.mindennapinlp.hu/content/intelligent-purchasing-approaches-todays-vehicle-customers “Viola”))

  39. November 8th, 2015 at 10:11 | #39

    great blog I enjoy playing the irish lottery

  40. November 8th, 2015 at 17:07 | #40

    excellent blog I’m a big soccer fan from holland

  41. November 12th, 2015 at 19:10 | #41

    I enjoy what you guys are usually up too. This type of clever work and coverage! Keep up the very good works guys I’ve incorporated you guys to blogroll.

  42. November 23rd, 2015 at 12:39 | #42

    Very good information. Lucky me I recently found your site by accident (stumbleupon).

  43. November 23rd, 2015 at 12:39 | #43

    Very good information. Lucky me I recently found your site by accident (stumbleupon). thankss

  44. November 26th, 2015 at 14:31 | #44


  45. November 26th, 2015 at 14:31 | #45


  46. December 29th, 2015 at 09:42 | #46

    thanks admin nice post good shared

  47. January 7th, 2016 at 02:00 | #47

    I like what you guys tend to be up too. This kind of clever work and reporting! Keep up the very good works guys I’ve you guys to my own blogroll.

  48. January 11th, 2016 at 16:02 | #48

    thanks admin nice post good shareds

  49. January 16th, 2016 at 12:30 | #49

    very nice

  50. January 18th, 2016 at 10:32 | #50

    voov thnaksss cds

Comment pages
1 2 1398
Comments are closed.