Javascript typeof object is string

JavaScript typeof

In JavaScript there are 5 different data types that can contain values:

There are 6 types of objects:

And 2 data types that cannot contain values:

The typeof Operator

You can use the typeof operator to find the data type of a JavaScript variable.

Example

typeof «John» // Returns «string»
typeof 3.14 // Returns «number»
typeof NaN // Returns «number»
typeof false // Returns «boolean»
typeof [1,2,3,4] // Returns «object»
typeof // Returns «object»
typeof new Date() // Returns «object»
typeof function () <> // Returns «function»
typeof myCar // Returns «undefined» *
typeof null // Returns «object»

  • The data type of NaN is number
  • The data type of an array is object
  • The data type of a date is object
  • The data type of null is object
  • The data type of an undefined variable is undefined *
  • The data type of a variable that has not been assigned a value is also undefined *

You cannot use typeof to determine if a JavaScript object is an array (or a date).

Primitive Data

A primitive data value is a single simple data value with no additional properties and methods.

The typeof operator can return one of these primitive types:

Example

typeof «John» // Returns «string»
typeof 3.14 // Returns «number»
typeof true // Returns «boolean»
typeof false // Returns «boolean»
typeof x // Returns «undefined» (if x has no value)

Complex Data

The typeof operator can return one of two complex types:

The typeof operator returns «object» for objects, arrays, and null.

The typeof operator does not return «object» for functions.

Example

typeof // Returns «object»
typeof [1,2,3,4] // Returns «object» (not «array», see note below)
typeof null // Returns «object»
typeof function myFunc()<> // Returns «function»

The typeof operator returns » object » for arrays because in JavaScript arrays are objects.

The Data Type of typeof

The typeof operator is not a variable. It is an operator. Operators ( + — * / ) do not have any data type.

But, the typeof operator always returns a string (containing the type of the operand).

The constructor Property

The constructor property returns the constructor function for all JavaScript variables.

Example

«John».constructor // Returns function String() <[native code]>
(3.14).constructor // Returns function Number() <[native code]>
false.constructor // Returns function Boolean() <[native code]>
[1,2,3,4].constructor // Returns function Array() <[native code]>
.constructor // Returns function Object() <[native code]>
new Date().constructor // Returns function Date() <[native code]>
function () <>.constructor // Returns function Function() <[native code]>

Читайте также:  Euclidean distance in python

You can check the constructor property to find out if an object is an Array (contains the word «Array»):

Example

Or even simpler, you can check if the object is an Array function:

Example

You can check the constructor property to find out if an object is a Date (contains the word «Date»):

Example

Or even simpler, you can check if the object is a Date function:

Example

Undefined

In JavaScript, a variable without a value, has the value undefined . The type is also undefined .

Example

Any variable can be emptied, by setting the value to undefined . The type will also be undefined .

Example

Empty Values

An empty value has nothing to do with undefined .

An empty string has both a legal value and a type.

Example

Null

In JavaScript null is «nothing». It is supposed to be something that doesn’t exist.

Unfortunately, in JavaScript, the data type of null is an object.

You can consider it a bug in JavaScript that typeof null is an object. It should be null .

You can empty an object by setting it to null :

Example

You can also empty an object by setting it to undefined :

Example

Difference Between Undefined and Null

undefined and null are equal in value but different in type:

typeof undefined // undefined
typeof null // object

null === undefined // false
null == undefined // true

The instanceof Operator

The instanceof operator returns true if an object is an instance of the specified object:

Example

const cars = [«Saab», «Volvo», «BMW»];

(cars instanceof Array);
(cars instanceof Object);
(cars instanceof String);
(cars instanceof Number);

The void Operator

The void operator evaluates an expression and returns undefined. This operator is often used to obtain the undefined primitive value, using «void(0)» (useful when evaluating an expression without using the return value).

Источник

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.

Читайте также:  Post xml rest php

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

Источник

Оцените статью