The purpose of JavaScript's typeof
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:
The variable is not declared
The value of the variable is undefined
For example:
> typeof undeclaredVariable === "undefined"
true
> var declaredVariable;
> typeof declaredVariable
'undefined'
&g t; 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 in an undeclared When the variable is on, 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 seems very complicated when completing 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; Whether the variable is declared by the declaration:
& & gt; Declared UndeClaredvariable
false
& & gt; Var Declaredvariable; DEFINED The operator is equivalent to defined(), and the declared operator above is equivalent to exists().
Determine whether a value is 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 one of the most famous weird manifestations of typeof ( Considered a bug): typeof null returned "object":
> typeof null
'object'
Translator's Note: This can only be said to be a bug in the original JavaScript implementation, and now the standard is This is standardized. 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 returns "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@justjavac)
Solved Solution: Don’t use typeof to do this task, use the following function instead:
function isDefined(x) {
return x !== null && x !== undefined;
}
another One possibility is to introduce a "default value operator". If myValue is not defined, the following expression will return defaultValue:
myValue ?? defaultValue
The above expression is equivalent to:
(myValue !== undefined && myValue !== null) ? myValue : defaultValue
Or:
myValue ??= defaultValue
is actually 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 encountered attribute whose value is undefined or null when traversing the attributes layer by layer:
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
Distinguish between object values and primitive values
The following function is used to detect whether x Is an object value:
function isObject(x) {
return (typeof x === "function"
}Problem: The above detection is more complicated because typeof treats functions and objects as different types, and typeof null returns "object". Solution: The following method is also often used to detect objects Value: function isObject2(x) { return x === Object(x);}Warning: You may think that you can use instanceof Object to detect here, but instanceof uses an object by using The prototype is used to determine the instance relationship, so what to do with objects without prototypes: > var obj = Object.create(null);> Object.getPrototypeOf(obj)nullobj Indeed is an object, but it is not an instance of any value: > typeof obj'object'> obj instanceof ObjectfalseIn 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. & & Gt; object.getprototypeof (object.prototype) null & gt; Typeoflact.protothpe'Object' & gt; Object.Prototype What is the type of Object lFalse original 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": 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 can not only return the type of the original value, but also the object The internal [[Class]] attribute of the value. Here is how to implement this function (Translator's Note: $.type in jQuery is such an implementation) Whether a certain value is a functiontypeof 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, 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. OverviewThe following mentioned should be the most urgently needed 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 Check a variable Had such a requirement been declared, it might not be necessary to have its own operator.
Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
