Home Web Front-end JS Tutorial Introduction to the use of typeof in JavaScript_Basic knowledge

Introduction to the use of typeof in JavaScript_Basic knowledge

May 16, 2016 pm 05:37 PM
javascript 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:

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 of this Website
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

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles