[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/typeof#typeof_null [Back]  [Original]

typeof - JavaScript | MDN

Dieser Inhalt wurde automatisch aus dem Englischen bersetzt, und kann Fehler enthalten. Erfahre mehr ber dieses Experiment.

View in English Always switch to English

typeof

Baseline Weitgehend verfgbar

Diese Funktion ist gut etabliert und funktioniert auf vielen Gerten und in vielen Browserversionen. Sie ist seit Juli 2015 browserbergreifend verfgbar.

Der typeof Operator gibt einen String zurck, der den Typ des Werts des Operanden angibt.

In diesem Artikel

Probieren Sie es aus

console.log(typeof 42);
// Expected output: "number"

console.log(typeof "blubber");
// Expected output: "string"

console.log(typeof true);
// Expected output: "boolean"

console.log(typeof undeclaredVariable);
// Expected output: "undefined"

Syntax

js
typeof operand

Parameter

operand

Ein Ausdruck, der das Objekt oder das Primitive darstellt, dessen Typ zurckgegeben werden soll.

Beschreibung

Die folgende Tabelle fasst die mglichen Rckgabewerte von typeof zusammen. Fr weitere Informationen ber Typen und Primitives siehe auch die Seite JavaScript-Datenstrukturen.

Typ Ergebnis
Undefined "undefined"
Null "object" (Grund)
Boolean "boolean"
Number "number"
BigInt "bigint"
String "string"
Symbol "symbol"
Function (implementiert [[Call]] in ECMA-262-Terms; Klassen sind ebenfalls Funktionen) "function"
Jedes andere Objekt "object"

Diese Liste der Werte ist vollstndig. Es sind keine spezifikationskonformen Engines bekannt, die andere Werte als die aufgelisteten produzieren (oder historisch produziert haben).

Beispiele

Grundlegende Nutzung

js
// 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

js
// This stands since the beginning of JavaScript
typeof null === "object";

In der ersten Implementierung von JavaScript wurden JavaScript-Werte als Typ-Tag und Wert dargestellt. Das Typ-Tag fr Objekte war 0. null wurde als NULL-Zeiger (0x00 auf den meisten Plattformen) dargestellt. Folglich hatte null 0 als Typ-Tag, daher der typeof Rckgabewert "object". (Referenz)

Ein Fix wurde fr ECMAScript vorgeschlagen (via Opt-in), aber wurde abgelehnt. Er htte dazu gefhrt, dass typeof null === "null".

Verwendung des new Operators

Alle Konstruktorfunktionen, die mit new aufgerufen werden, geben Nicht-Primitives zurck ("object" oder "function"). Die meisten geben Objekte zurck, mit der bemerkenswerten Ausnahme der Function, die eine Funktion zurckgibt.

js
const str = new String("String");
const num = new Number(100);

typeof str; // "object"
typeof num; // "object"

const func = new Function();

typeof func; // "function"

Bedarf an Klammern in der Syntax

Der typeof Operator hat eine hhere Prioritt als binre Operatoren wie die Addition (+). Daher sind Klammern erforderlich, um den Typ eines Additionsresultats zu evaluieren.

js
// Parentheses can be used for determining the data type of expressions.
const someData = 99;

typeof someData + " foo"; // "number foo"
typeof (someData + " foo"); // "string"

Interaktion mit nicht deklarierten und nicht initialisierten Variablen

typeof funktioniert mit nicht deklarierten Identifikatoren und gibt "undefined" zurck, anstatt einen Fehler zu werfen.

js
typeof undeclaredVariable; // "undefined"

Die Verwendung von typeof bei lexikalischen Deklarationen (let const, using await using, und class) im selben Block vor der Deklarationsstelle wird jedoch einen ReferenceError werfen. Block-skopierte Variablen befinden sich in einer temporren Totzone vom Beginn des Blocks bis die Initialisierung verarbeitet ist; whrend dieser Zeit wird ein Fehler geworfen, wenn auf sie zugegriffen wird.

js
typeof newLetVariable; // ReferenceError
typeof newConstVariable; // ReferenceError
typeof newClass; // ReferenceError

let newLetVariable;
const newConstVariable = "hello";
class newClass {}

Siehe typeof Operator und undefined fr weitere Details.

Auergewhnliches Verhalten von document.all

Alle aktuellen Browser legen ein nicht-standardisiertes Host-Objekt document.all mit dem Typ undefined offen.

js
typeof document.all === "undefined";

Obwohl document.all auch falsy ist und lose gleich zu undefined, ist es nicht undefined. Der Fall, dass document.all den Typ "undefined" hat, wird in den Webstandards als eine "willkrliche Verletzung" des ursprnglichen ECMAScript-Standards fr die Webkompatibilitt klassifiziert.

Benutzerdefinierte Methode fr spezifischeren Typ

typeof ist sehr ntzlich, aber es ist nicht so vielseitig, wie es erforderlich sein knnte. Zum Beispiel ist typeof [] "object", ebenso wie typeof new Date(), typeof /abc/, usw.

Fr grere Spezifitt beim berprfen von Typen prsentieren wir hier eine benutzerdefinierte type(value) Funktion, die weitgehend das Verhalten von typeof nachahmt, aber fr Nicht-Primitives (d.h. Objekte und Funktionen) einen spezifischeren Typnamen zurckgibt, wo mglich.

js
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;
}

Zum berprfen potenziell nicht existierender Variablen, die sonst einen ReferenceError werfen wrden, verwenden Sie typeof nonExistentVar === "undefined", da dieses Verhalten nicht mit benutzerdefiniertem Code nachgeahmt werden kann.

Spezifikationen

Spezifikation
ECMAScript 2027 LanguageSpecification
# sec-typeof-operator

Browser-Kompatibilitt

Siehe auch


Web Proxy Viewer  |  New URL  |  Original Page