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

Understanding typeof, instanceof and constructor in JavaScript

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

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

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

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.

Wrap-up

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

  1. September 21st, 2011 at 02:01 | #1
  2. February 15th, 2012 at 05:52 | #2
  3. March 12th, 2012 at 04:55 | #3
  4. July 14th, 2012 at 02:53 | #4
  5. November 6th, 2012 at 15:22 | #5
  6. December 15th, 2012 at 11:04 | #6

Comments parsed as Markdown.