[javascript] What is the difference between typeof and instanceof and when should one be used vs. the other?

I've discovered some really interesting (read as "horrible") behavior in Safari 5 and Internet Explorer 9. I was using this with great success in Chrome and Firefox.

if (typeof this === 'string') {
    doStuffWith(this);
}

Then I test in IE9, and it doesn't work at all. Big surprise. But in Safari, it's intermittent! So I start debugging, and I find that Internet Explorer is always returning false. But the weirdest thing is that Safari seems to be doing some kind of optimization in its JavaScript VM where it is true the first time, but false every time you hit reload!

My brain almost exploded.

So now I've settled on this:

if (this instanceof String || typeof this === 'string')
    doStuffWith(this.toString());
}

And now everything works great. Note that you can call "a string".toString() and it just returns a copy of the string, i.e.

"a string".toString() === new String("a string").toString(); // true

So I'll be using both from now on.

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to instanceof

How to efficiently check if variable is Array or Object (in NodeJS & V8)? How to perform runtime type checking in Dart? Use of "instanceof" in Java What is the 'instanceof' operator used for in Java? Is it possible to use the instanceof operator in a switch statement? instanceof Vs getClass( ) How to see if an object is an array without using reflection? What is the instanceof operator in JavaScript? How to check if a subclass is an instance of a class at runtime? Java: Instanceof and Generics

Examples related to typeof

Get class name of object as string in Swift Why does typeof array with objects return "object" and not "array"? Get type of all variables How to cast Object to its actual type? typeof operator in C When and where to use GetType() or typeof()? How do I get the type of a variable? How to efficiently check if variable is Array or Object (in NodeJS & V8)? Better way to get type of a Javascript variable? C# switch on type