Home > Article > Web Front-end > Introduction to the use of typeof in JavaScript_Basic knowledge
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.
The premise of reading this article is that you should now know the difference between primitive values and object values.
Check whether a variable exists and whether it has a value
typeof will return "undefined" in two cases:
1. The variable is not declared
2. The value of the variable is undefined
For example:
> var declaredVariable;
> typeof declaredVariable
'undefined'
> typeof undefined
'undefined'
There are other ways to detect whether a value is undefined:
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:
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:
> (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 very complicated to complete such a task.
Solution: This kind of operation is not very common, so some people think there is no need to find a better solution. But maybe someone will come up with a special operator:
> var declaredVariable;
> defined declaredVariable
false
Alternatively, maybe someone needs an operator that detects whether a variable is declared:
> var declaredVariable;
> declared declaredVariable
true
Translator’s Note: In perl, the above defined operator is equivalent to defined(), and the above declared operator is equivalent to exists().
Determine whether a value is not equal to undefined or null
Problem: If you want to detect whether a value has been defined (the value is neither undefined nor null), then you have encountered typeof. A famous weird behavior (considered a bug): typeof null returns "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 regulated. V8 once corrected and implemented typeof null === "null", but it ultimately proved unfeasible. http://wiki.ecmascript.org/doku.php?id=harmony:typeof_null.
(Annotation: typeof will return "object" when operating on null. This is a bug in the JavaScript language itself. Unfortunately, this bug will never be fixed because too much existing code already relies on this Performance. But is null an object? There is a discussion on this issue on stackoverflow: http://stackoverflow.com/questions/801032/null-object-in-javascript/7968470#7968470@justjavac)
Solution: Don’t use typeof for this task, use a function like this instead:
Another possibility is to introduce a "default value operator", where the following expression returns defaultValue if myValue is undefined:
The above expression is equivalent to:
Or:
is actually a simplification of the following statement:
When you access a nested property, such as bar, you may need the help of this operator:
If obj or obj.foo is undefined, the above expression will throw an exception. An operator .?? allows the above expression to return the first encountered attribute whose value is undefined or null when traversing the attributes layer by layer:
The above expression is equivalent to:
Distinguish between object values and primitive values
The following function is used to check whether x is an object value:
Problem: The above detection is more 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:
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 to do with objects without prototypes:
obj is indeed an object, but it is not an instance of any value:
In practice, you may rarely encounter such an object, but it does exist and has its uses.
Translator's Note: Object.prototype is the only built-in object without a prototype.
What is the type of a primitive value?
typeof is the best way to check the type of a primitive value.
Problem: You must be aware of the weird behavior of typeof null.
Workaround: The following function can fix this problem (only for this use case).
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: $.type in jQuery is such an implementation)
Whether a value is a function
typeof can be used to detect whether a value is a function.
In principle, instanceof Function can also detect this requirement. At first glance, it seems that the writing method is more elegant. However, browsers have a quirk: every frame and window has its own global variables. Therefore, if you pass an object from one frame to another, instanceof will not work properly because the two frames have different constructors. This is why there is Array.isArray() method in ECMAScript5. It would be nice if there was a cross-framework method for checking whether an object is an instance of a given constructor. The getTypeName() above is a workaround available, but there may be a more fundamental solution.
Overview
The following mentioned should be the most urgently needed features in JavaScript at present, which 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 to detect whether an object is an instance of a specified constructor
For requirements like checking whether a variable has been declared, it may not be necessary to have its own operator.