Typeof in JavaScript is actually very complex. It can be used to do many things, but it also has many weird behaviors. This article lists its multiple uses, and also points out existing problems and solutions.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FOperators%2Ftypeof
> typeof undefined
'undefined'
> typeof null // well-known bug
'object'
> typeof true
'boolean'
>typeof 123
'number'
> typeof "abc"
'string'
> typeof function() {}
'function'
> typeof {}
'object'
> typeof []
'object'
> typeof unknownVariable
'undefined'
1. Check whether a variable exists and has a value.
typeof will return "undefined" in two situations: when a variable is not declared, and when the value of a variable is undefined. For example:
> typeof undeclaredVariable === "undefined" true > var declaredVariable; > typeof declaredVariable 'undefined' > typeof undefined 'undefined'
There are other ways to detect whether a value is undefined:
> var value = undefined; > value === undefined true
But if this method is used on an undeclared variable, an exception will be thrown, because only typeof can detect undeclared variables normally without reporting an error:
> undeclaredVariable === undefined ReferenceError: undeclaredVariable is not defined
Note: Uninitialized variables, formal parameters without passed parameters, and non-existent properties will not have the above problems, because they are always accessible and the value is always undefined:
> var declaredVariable; > declaredVariable === undefined true > (function (x) { return x === undefined }()) true > ({}).foo === undefined true
Translator's Note: Therefore, if you want to detect the existence of a global variable that may not be declared, you can also use if(window.maybeUndeclaredVariable){}
Problem: typeof is cumbersome to accomplish such a task.
Solution: This kind of operation is not very common, so some people feel that there is no need to find a better solution. But maybe someone will propose a special operator:
> defined undeclaredVariable false > var declaredVariable; > defined declaredVariable false
Or, maybe one also needs an operator that detects whether a variable is declared:
> declared undeclaredVariable false > var declaredVariable; > declared declaredVariable true
Translator's Note: In Perl, the defined operator above is equivalent to defined(), and the declared operator above is equivalent to exists().
2. Determine whether a value is not equal to undefined or null.
Problem: If you want to check whether a value has been defined (the value is neither undefined nor null), then you encounter one of typeof's most famous quirks (considered a bug): typeof null returns "object":
> typeof null 'object'
Translator's Note: This can only be said to be a bug in the original JavaScript implementation, and this is how the standard is now standardized. V8 once revised and implemented typeof null === "null", but it ultimately proved unfeasible. http://wiki .ecmascript.org/doku.php?id=harmony:typeof_null
Solution: Don't use typeof for this task, use a function like this instead:
function isDefined(x) { return x !== null && x !== undefined; }
Another possibility is to introduce a "default value operator", where the following expression returns defaultValue if myValue is not defined:
myValue ?? defaultValue
The above expression is equivalent to:
(myValue !== undefined && myValue !== null) ? myValue : defaultValue
Or:
myValue ??= defaultValue
In fact, it is a simplification of the following statement:
myValue = myValue ?? defaultValue
When you access a nested property, such as bar, you may need the help of this operator:
obj.foo.bar
If obj or obj.foo is undefined, the above expression will throw an exception. An operator.?? allows the above expression to return the first value encountered when traversing the properties layer by layer. Properties that are undefined or null:
obj.??foo.??bar
The above expression is equivalent to:
(obj === undefined || obj === null) ? obj : (obj.foo === undefined || obj.foo === null) ? obj.foo : obj.foo.bar
3. Distinguish between object values and primitive values
The following function tests whether x is an object value:
function isObject(x) { return (typeof x === "function" || (typeof x === "object" && x !== null)); }
Problem: The above detection is complicated because typeof regards functions and objects as different types, and typeof null returns "object".
Solution: The following method is also often used to detect object values:
function isObject2(x) { return x === Object(x); }
Warning: You may think that you can use instanceof Object to detect here, but instanceof determines the instance relationship by using the prototype of an object, so what about objects without prototypes:
> var obj = Object.create(null); > Object.getPrototypeOf(obj) null
obj is indeed an object, but it is not an instance of any value:
> typeof obj 'object' > obj instanceof Object false
In practice, you may rarely encounter such an object, but it does exist and has its uses.
Translator's Note: Object.prototype is an object that exists by default and has no prototype.
>Object.getPrototypeOf(Object.prototype)null>typeof Object.prototype'object'>Object.prototype instanceof Object false
4.What is the type of primitive value?
typeof is the best way to check the type of a primitive value.
> typeof "abc" 'string' > typeof undefined 'undefined'
Problem: You must be aware of the weird behavior of typeof null.
> typeof null // Be careful! 'object'
Solution: The following function can fix this problem (only for this use case).
function getPrimitiveTypeName(x) { var typeName = typeof x; switch(typeName) { case "undefined": case "boolean": case "number": case "string": return typeName; case "object": if (x == = null) { return "null"; } default: // None of the previous judgments passed throw new TypeError("The parameter is not a primitive value: "+x); } }
A better solution: implement a function getTypeName(), which in addition to returning the type of the original value, can also return the internal [[Class]] attribute of the object value. Here is how to implement this function (Translator's Note: jQuery $.type is such an implementation)
5. Whether a certain value is a function
typeof can be used to detect whether a value is a function. > typeof function () {} 'function' > typeof Object.prototype.toString 'function'
In principle, instanceof Function can also detect this requirement. At first glance, it seems that the writing method is more elegant. However, the browser has a quirk: each frame and window has its own global variables. Therefore, if you put a certain frame in If the object is passed to another framework, instanceof will not work properly because the two frameworks have different constructors. This This is why there is an Array.isArray() method in ECMAScript 5. It would be nice if there was a cross-framework method for checking whether an object is an instance of a given constructor. The above getTypeName( ) is a workaround available, but there may be a more fundamental solution.
6.Overview
The following mentioned should be the most urgently needed features in JavaScript at present, and can replace some of the functional features of typeof’s current responsibilities:
isDefined() (such as Object.isDefined()): can be used as a function or an operator
isObject()
getTypeName()
A cross-framework mechanism for detecting whether an object is an instance of a specified constructor
The need to check whether a variable has been declared may not require its own operator.