Home  >  Article  >  Web Front-end  >  How to use typeof in JavaScript

How to use typeof in JavaScript

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-06-09 14:31:076787browse

In js, the usage of typeof is "typeof (expression)" or "typeof variable name". Typeof is a unary operation, placed before an operand, and the operand can be of any type. Its return value is a string describing the type of the operand.

How to use typeof in JavaScript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

JS is a weak language. It does not need to determine the type of the variable when declaring it. JS will automatically determine it at runtime. So how to determine the type of a variable? js provides the typeof operator to detect the type of a variable.

1. The syntax of typeof

Typeof is an operator. There are two ways to use it: typeof (expression) and typeof variable name. The first one is to operate on the expression. The second one is to operate on the expression. The second is to perform operations on variables.

2. The return value of typeof

The return type of the typeof operator is a string, and the values ​​include the following:

1. 'undefined' --Undefined Variable or value

2. 'Boolean'-Boolean type variable or value

3. 'String'-String type variable or value

## 4.. 'number'                                                                                              

6. 'Function'-Functional variable or value

3. Simple example

    console.log(typeof a);    //'undefined'
    console.log(typeof(true));  //'boolean'
    console.log(typeof '123');  //'string'
    console.log(typeof 123);   //'number'
    console.log(typeof NaN);   //'number'
    console.log(typeof null);  //'object'    
    var obj = new String();
    console.log(typeof(obj));    //'object'
    var  fn = function(){};
    console.log(typeof(fn));  //'function'
    console.log(typeof(class c{}));  //'function'

Summary: Typeof operator is used to determine the type of object, but for some for some Created objects will all return 'object'. Sometimes we need to determine whether the instance is an instance of an object. At this time, we need to use the instanceof operator. The related usage of the instanceof operator will be recorded later.

[Recommended learning:

javascript advanced tutorial

]

The above is the detailed content of How to use typeof in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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