(blog-of ‘Alex’)

A personal blog about software development and other things. All opinions expressed here are my own, unless explicitly stated.

When typeof string != string

Javascript may seem like a simple language at a first glance, however it never stops surprising as you start doing non-trivial stuff with it.

Consider the following code:

var s = "asd"
var f = function() { return typeof(this) }

An expression typeof(s) returns “string” (as it is expected), but f.call(s) returns “object”!

To make matters worse consider the following snippet:

var s = "asd"
var f = function() { return this instanceof String }

An expression f.call(s) returns true, but (s instanceof String) returns false!

In short: the reason why it happens is because this should always be an object (instanceof operator works only for objects, e.g. string literal is not an instance of String itself) in contrast typeof operator always returns “object” when applied to any instance of either builtin ‘class’ or a user-defined one.


Copied from http://alexshabanov.com/2010/05/12/when-typeof-string-string/