What is the quickest and cleanest way to test if a var holds immutable data (i.e. is string, number, boolean, null, undefined)?
E.g. When var test is mutable, the following is legal:
var test = {};
//the next 2 lines work because `test` has mutable data
test.someFun = function () { alert(this); };
test.someFun();
but when var test is immutable, it’s illegal:
var test = "string";
//the next 2 lines are invalid, as `test` is a primitive
test.someFun = function () { alert(this); };
test.someFun();
jball pointed out the following:
Seems a valid point to me. So if you want to do this check across different scopes you will need to use the workaround:
I would try to avoid the use of iframes though.
The null check is needed because
typeof(null)is equal to'object'.EDIT:
box9 and jball did some performance testing on all the methods proposed (+1 for that). I used Chrome, Firefox and Internet Explorer. The result are as expected. These two methods are the fastest. On Chrome and Firefox the
typeofversion is the fastest. On Internet Explorer theinstanceofversion was the fastest. But the difference in speed between these two methods were minor. Personally I’d still go with theinstanceofmethod if I could because it’s cleaner.