search
HomeWeb Front-endJS TutorialIntroduction 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:

Copy code The code is as follows:

> typeof undeclaredVariable === "undefined"
true

> var declaredVariable;
> typeof declaredVariable
'undefined'

> typeof undefined
'undefined'

There are other ways to detect whether a value is undefined:

Copy code The code is as follows:

> 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:

Copy code The code is as follows:

> 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:

Copy code The code is as follows:

> 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 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:

Copy code The code is as follows:

> defined undeclaredVariable
false

> var declaredVariable;
> defined declaredVariable
false

Alternatively, maybe someone needs an operator that detects whether a variable is declared:

Copy code The code is as follows:

> declared undeclaredVariable
false

> 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":

Copy code The code is as follows:

> 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 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:

Copy code The code is as follows:

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 undefined:

Copy code The code is as follows:

myValue ?? defaultValue

The above expression is equivalent to:

Copy code The code is as follows:

(myValue !== undefined && myValue !== null ) ? myValue : defaultValue

Or:

Copy code The code is as follows:

myValue ??= defaultValue

is actually a simplification of the following statement:

Copy code The code is as follows:

myValue = myValue ?? defaultValue

When you access a nested property, such as bar, you may need the help of this operator:

Copy code The code is as follows:

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:

Copy code The code is as follows:

obj.??foo.??bar

The above expression is equivalent to:

Copy code The code is as follows:

(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 check whether x is an object value:

Copy code The code is as follows:

function isObject(x) {
return (typeof x === "function"
|| (typeof x === "object" && x !== null));
}

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:

Copy code The code is as follows:

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 to do with objects without prototypes:

Copy code The code is as follows:

> var obj = Object.create(null);
> Object.getPrototypeOf(obj)
null

obj is indeed an object, but it is not an instance of any value:

Copy code The code is as follows:

> 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 the only built-in object without a prototype.

Copy code The code is as follows:

>Object.getPrototypeOf(Object.prototype)
null
>typeof Object.prototype
'object'
>Object.prototype instanceof Object
false

What is the type of a primitive value?
typeof is the best way to check the type of a primitive value.

Copy code The code is as follows:

> typeof "abc"
'string'
> typeof undefined
'undefined'

Problem: You must be aware of the weird behavior of typeof null.

Copy code The code is as follows:

> typeof null // Be careful!
'object'

Workaround: The following function can fix this problem (only for this use case).

Copy code The code is as follows:

function getPrimitiveTypeName(x) {
var typeName = typeof x;
switch(typeName) {
case "undefined":
case "boolean":
case "number":
case "string":
return type Name;
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: $.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.

Copy code The code is as follows:

> 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.

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.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

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

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

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

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.