Dec 10, 2013

JavaScript typeof vs instanceof

Reading is good

And I assume almost no one reading this post would disagree that reading is good. And once you agree with that, then it follows that good books are valuable. Good books alter our thinking. Good books can be life-changing.

I have been reading Professional JavaScript for Web Developers (3rd ed). It find many little details of the JavaScript language that I almost never comes across when simply learning to code or following a tutorial or a newsletter.

Theory and Practice in the world

I suppose this is the dichotomy between theory and practice that many professionals experience, whatever their profession might be. For example, a good trader may be familiar with modern portfolio theory, and be able to outline the efficient frontier. Then, on the trading floor, find that day-to-day, she never really applies that theory or knowledge. However, there maybe a longer-term project, or a strategic shift in investment for which that knowledge may make the difference between success and failure. Likewise, when scaffolding a JavaScript app using a tool like Yeoman or Meteor, many programmers may never think about memory management or garbage collection.  Do you know how it's done in JavaScript? And how will you apply them in your application, even if you were familiar with those concepts?

We live in a world of changing contexts, between clean theoretical Platonic concepts, and a messy practical application where little details could matter, or may be totally immaterial.

It looks quirky for now - typeof and instanceof

For now, the details look very quirky to me. I'm sure it will change over time as I see other contexts, and find cases of the theory applied in practice. With that statement of faith in mind, it's time to play on the console (Using a Chrome browser, F12 key on a PC brings up the developer tool, which includes a console).

According  to the book, typeof is used to determine if a variable is a primitive type, whereas instanceof operator is used to determine the type of an Object. Here are some examples - play with other variations in your console.

typeof "anything"  // "string"
typeof 3           // "number"
typeof null        // "object"
typeof [1,2,"3"]   // "object"
typeof {}          // "object"

So, lots of things are object. Let's move on. Keep in mind that primitives are not objects.

var array = [1,2,3]
array instanceof Array    // true
array instanceof Object   // true
Array instanceof Object   // true
Array instanceof Array    // false

So, an array is an object, not an instance of another Array.

Check out other technical things I am learning on http://pleaserefactor.com/.

No comments: