- Оператор typeof
- Синтаксис
- Пример
- Пример
- Пример
- Пример
- Пример
- Пример
- Пример
- Пример
- Пример
- Смотрите также
- typeof
- Try it
- Syntax
- Parameters
- Description
- Examples
- Basic usage
- typeof null
- Using new operator
- Need for parentheses in syntax
- Interaction with undeclared and uninitialized variables
- Exceptional behavior of document.all
- Custom method that gets a more specific type
- Specifications
- Browser compatibility
- See also
- How to Check if a Variable is of Function Type
- The typeof Operator
- The instanceof Operator
- The toString() Method
- JavaScript Functions
- Related Resources
Оператор typeof
Оператор typeof позволяет определить тип параметра (число, строка, объект). Оператор возвращает строку, содержащую тип ( ‘number’ , ‘string’ , ‘object’ ).
Для null оператор возвращает ‘object’ (это признанная ошибка языка). Для функций оператор возвращает ‘function’ . Это сделано для удобства, так как типа ‘function’ не существует.
Синтаксис
У оператора typeof есть 2 синтаксиса (оба синтаксиса работают одинаково):
Пример
Давайте посмотрим, как typeof работает с числом:
В результате выполненного кода мы получим значение number :
Пример
Теперь давайте зададим в параметре строку:
Результат выполнения кода:
Пример
Теперь укажем в параметре булевое значение true :
Результат выполнения кода:
Пример
Давайте посмотрим какой тип у значения undefined :
После выполнения кода мы получим также undefined :
Пример
Теперь давайте узнаем тип пустого объекта:
Результат выполнения кода:
Пример
А теперь узнаем тип пустого массива:
В результате также получим ‘object’ :
Пример
Давайте узнаем тип значения null :
В результате также получим ‘object’ , что является признанной ошибкой языка:
Пример
Теперь определим тип пустой функции:
После выполнения кода мы получим ‘function’ , несмотря на то, что такого типа не существует. Данная строка нужна для удобства пользователя при определении функции:
Пример
Напишем функцию, которая будет выводить только числа:
Смотрите также
- функцию isNaN ,
которая осуществляет проверку на NaN - функцию isFinite ,
которая проверяет число на конечность
typeof
The typeof operator returns a string indicating the type of the operand’s value.
Try it
Syntax
Parameters
An expression representing the object or primitive whose type is to be returned.
Description
The following table summarizes the possible return values of typeof . For more information about types and primitives, see also the JavaScript data structure page.
Type | Result |
---|---|
Undefined | «undefined» |
Null | «object» (reason) |
Boolean | «boolean» |
Number | «number» |
BigInt | «bigint» |
String | «string» |
Symbol | «symbol» |
Function (implements [[Call]] in ECMA-262 terms; classes are functions as well) | «function» |
Any other object | «object» |
This list of values is exhaustive. No spec-compliant engines are reported to produce (or had historically produced) values other than those listed.
Examples
Basic usage
// Numbers typeof 37 === "number"; typeof 3.14 === "number"; typeof 42 === "number"; typeof Math.LN2 === "number"; typeof Infinity === "number"; typeof NaN === "number"; // Despite being "Not-A-Number" typeof Number("1") === "number"; // Number tries to parse things into numbers typeof Number("shoe") === "number"; // including values that cannot be type coerced to a number typeof 42n === "bigint"; // Strings typeof "" === "string"; typeof "bla" === "string"; typeof `template literal` === "string"; typeof "1" === "string"; // note that a number within a string is still typeof string typeof typeof 1 === "string"; // typeof always returns a string typeof String(1) === "string"; // String converts anything into a string, safer than toString // Booleans typeof true === "boolean"; typeof false === "boolean"; typeof Boolean(1) === "boolean"; // Boolean() will convert values based on if they're truthy or falsy typeof !!1 === "boolean"; // two calls of the ! (logical NOT) operator are equivalent to Boolean() // Symbols typeof Symbol() === "symbol"; typeof Symbol("foo") === "symbol"; typeof Symbol.iterator === "symbol"; // Undefined typeof undefined === "undefined"; typeof declaredButUndefinedVariable === "undefined"; typeof undeclaredVariable === "undefined"; // Objects typeof a: 1 > === "object"; // use Array.isArray or Object.prototype.toString.call // to differentiate regular objects from arrays typeof [1, 2, 4] === "object"; typeof new Date() === "object"; typeof /regex/ === "object"; // The following are confusing, dangerous, and wasteful. Avoid them. typeof new Boolean(true) === "object"; typeof new Number(1) === "object"; typeof new String("abc") === "object"; // Functions typeof function () > === "function"; typeof class C > === "function"; typeof Math.sin === "function";
typeof null
// This stands since the beginning of JavaScript typeof null === "object";
In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0 . null was represented as the NULL pointer ( 0x00 in most platforms). Consequently, null had 0 as type tag, hence the typeof return value «object» . (reference)
A fix was proposed for ECMAScript (via an opt-in), but was rejected. It would have resulted in typeof null === «null» .
Using new operator
All constructor functions called with new will return non-primitives ( «object» or «function» ). Most return objects, with the notable exception being Function , which returns a function.
const str = new String("String"); const num = new Number(100); typeof str; // "object" typeof num; // "object" const func = new Function(); typeof func; // "function"
Need for parentheses in syntax
The typeof operator has higher precedence than binary operators like addition ( + ). Therefore, parentheses are needed to evaluate the type of an addition result.
// Parentheses can be used for determining the data type of expressions. const someData = 99; typeof someData + " Wisen"; // "number Wisen" typeof (someData + " Wisen"); // "string"
Interaction with undeclared and uninitialized variables
typeof is generally always guaranteed to return a string for any operand it is supplied with. Even with undeclared identifiers, typeof will return «undefined» instead of throwing an error.
typeof undeclaredVariable; // "undefined"
However, using typeof on lexical declarations ( let const , and class ) in the same block before the line of declaration will throw a ReferenceError . Block scoped variables are in a temporal dead zone from the start of the block until the initialization is processed, during which it will throw an error if accessed.
typeof newLetVariable; // ReferenceError typeof newConstVariable; // ReferenceError typeof newClass; // ReferenceError let newLetVariable; const newConstVariable = "hello"; class newClass >
Exceptional behavior of document.all
All current browsers expose a non-standard host object document.all with type undefined .
typeof document.all === "undefined";
Although document.all is also falsy and loosely equal to undefined , it is not undefined . The case of document.all having type «undefined» is classified in the web standards as a «willful violation» of the original ECMAScript standard for web compatibility.
Custom method that gets a more specific type
typeof is very useful, but it’s not as versatile as might be required. For example, typeof [] is «object» , as well as typeof new Date() , typeof /abc/ , etc.
For greater specificity in checking types, here we present a custom type(value) function, which mostly mimics the behavior of typeof , but for non-primitives (i.e. objects and functions), it returns a more granular type name where possible.
function type(value) if (value === null) return "null"; > const baseType = typeof value; // Primitive types if (!["object", "function"].includes(baseType)) return baseType; > // Symbol.toStringTag often specifies the "display name" of the // object's class. It's used in Object.prototype.toString(). const tag = value[Symbol.toStringTag]; if (typeof tag === "string") return tag; > // If it's a function whose source code starts with the "class" keyword if ( baseType === "function" && Function.prototype.toString.call(value).startsWith("class") ) return "class"; > // The name of the constructor; for example `Array`, `GeneratorFunction`, // `Number`, `String`, `Boolean` or `MyCustomClass` const className = value.constructor.name; if (typeof className === "string" && className !== "") return className; > // At this point there's no robust way to get the type of value, // so we use the base implementation. return baseType; >
For checking potentially non-existent variables that would otherwise throw a ReferenceError , use typeof nonExistentVar === «undefined» because this behavior cannot be mimicked with custom code.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
How to Check if a Variable is of Function Type
There are several methods in JavaScript that can check whether a variable is of function or not. Let’s discuss each of them and find the fastest solution to the question.
The typeof Operator
You can use the typeof operator to check the variable. It returns a string which indicates the type of the unevaluated operand.
Javascript typeof method
console.log(typeof » === ‘string’); console.log(typeof function() <> === ‘function’); console.log(typeof true === ‘boolean’); console.log(typeof Symbol() === ‘symbol’); console.log(typeof
The instanceof Operator
Another method can be the instanceof operator which checks the type of an object at run time. It return a corresponding boolean value, for example, either true or false to indicate if the object is of a particular type or not:
Javascript instanceof method
let str = new String(); let date = new Date(); console.log(str instanceof Object); console.log(str instanceof Date); console.log(str instanceof String); console.log(str instanceof Number); console.log(date instanceof Date); console.log(date instanceof Object); console.log(date instanceof String); console.log(date instanceof Number);
The typeof method appears to be the fastest in Chrome, but in Firefox the instanceof method is the winner.
The toString() Method
Another useful method is toString() . Each object has a toString() method, which is called when a value of string type is expected. If the method is not overridden, it will return the object type.
Javascript toString method
let arr = new Array(«Html», «Css», «Javascript», «Git»); let str = arr.toString(); console.log(«Showing string is : » + str );
JavaScript Functions
JavaScript functions are the main blocks of code that are designed to perform a particular task. Functions allow the code to be called many times without repetition. Variables that are defined inside a function cannot be accessed from anywhere outside that function, as it is defined only in the scope of the function.
Related Resources
- How to Check if an Object has a Specific Property in JavaScript
- How to Check if a Key Exists in JavaScript Object
- How to Check if a Value is an Object in JavaScript
- How to Check Whether an Object is a Date
- How to Check if the Variable is Undefined
- How to Unset a JavaScript Variable
- JavaScript Class Checking: «instanceof»
- JavaScript Data Types
- JavaScript Variables
- Javascript Objects
- JavaScript Functions