Home  >  Article  >  Web Front-end  >  The meaning of typeof in js

The meaning of typeof in js

下次还敢
下次还敢Original
2024-05-01 08:45:28823browse

The typeof operator is used to determine the type of a variable or expression in JavaScript and returns one of the following string values: "undefined": The variable is undefined or the value is undefined "boolean": The variable is a Boolean value "number": The variable is a number "string": The variable is a string "object": The variable is an object "function": The variable is a function "symbol": The variable is a Symbol type (ES6) "bigint": The variable is a BigInt type (ES2020 )

The meaning of typeof in js

typeof means in JavaScript

In JavaScript, typeof operator Used to determine the type of a variable or expression. It returns a string representing the type of variable or expression.

Usage:

<code class="javascript">typeof variable_or_expression;</code>

Where, variable_or_expression can be any valid JavaScript variable or expression.

Possible return values:

typeof The operator can return the following string values:

  • "undefined " - When the variable is undefined or has the value undefined.
  • "boolean" - When the variable is a boolean (true or false).
  • "number" - when the variable is a number.
  • "string" - when the variable is a string.
  • "object" - when the variable is an object.
  • "function" - when the variable is a function.
  • "symbol" - when the variable is of type Symbol (introduced in ES6).
  • "bigint" - when the variable is of type BigInt (introduced in ES2020).

Example:

<code class="javascript">console.log(typeof undefined); // "undefined"
console.log(typeof true); // "boolean"
console.log(typeof 42); // "number"
console.log(typeof "hello world"); // "string"
console.log(typeof {}); // "object"
console.log(typeof function() {}); // "function"
console.log(typeof Symbol()); // "symbol"
console.log(typeof 123n); // "bigint"</code>

typeof The operator can be used to check the type of a variable and perform different operations based on the type. For example, the following code block checks whether the variable x is a number, and if so, adds 1 to x:

<code class="javascript">const x = 42;

if (typeof x === "number") {
  x++;
}

console.log(x); // 43</code>

The above is the detailed content of The meaning of typeof in js. 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