Operador de tipo JavaScript

En este tutorial, aprenderá sobre el operador de tipo de JavaScript con la ayuda de ejemplos.

El typeofoperador devuelve el tipo de variables y valores. Por ejemplo,

 const a = 9; console.log(typeof a); // number console.log(typeof '9'); // string console.log(typeof false); // boolean

Sintaxis del tipo de operador

La sintaxis del typeofoperador es:

 typeof operand

Aquí, el operando es un nombre de variable o un valor.

typeof tipos

Los posibles tipos que están disponibles en JavaScript que typeofdevuelve el operador son:

Tipos tipo de resultado
String "cuerda"
Number "número"
BigInt "Empezando"
Boolean "booleano"
Object "objeto"
Symbol "símbolo"
undefined "indefinido"
null "objeto"
función "función"

Ejemplo 1: typeof para String

 const str1 = 'Peter'; console.log(typeof str1); // string const str2 = '3'; console.log(typeof str2); // string const str3 = 'true'; console.log(typeof str3); // string

Ejemplo 2: typeof para Number

 const number1 = 3; console.log(typeof number1); // number const number2 = 3.433; console.log(typeof number2); // number const number3 = 3e5 console.log(typeof number3); // number const number4 = 3/0; console.log(typeof number4); // number 

Ejemplo 3: typeof para BigInt

 const bigInt1 = 900719925124740998n; console.log(typeof bigInt1); // bigint const bigInt2 = 1n; console.log(typeof bigInt2); // bigint

Ejemplo 4: typeof para booleano

 const boolean1 = true; console.log(typeof boolean1); // boolean const boolean2 = false; console.log(typeof boolean2); // boolean

Ejemplo 5: typeof para Undefined

 let variableName1; console.log(typeof variableName1); // undefined let variableName2 = undefined; console.log(typeof variableName2); // undefined

Ejemplo 6: typeof para nulo

 const name = null; console.log(typeof name); // object console.log(typeof null); // object

Ejemplo 7: typeof para Symbol

 const symbol1 = Symbol(); console.log(typeof symbol1); // symbol const symbol2 = Symbol('hello'); console.log(typeof symbol2); // symbol

Ejemplo 8: typeof para Object

 let obj1 = (); console.log(typeof obj1); // object let obj2 = new String(); console.log(typeof obj2); // object let obj3 = (1, 3, 5, 8); console.log(typeof obj3); // object

Ejemplo 9: tipo de función

 let func = function () (); console.log(typeof func); // function // constructor function console.log(typeof String); // function console.log(typeof Number); // function console.log(typeof Boolean); // function

Usos del tipo de operador

  • El typeofoperador se puede utilizar para verificar el tipo de variable en un punto en particular. Por ejemplo,
 let count = 4; console.log(typeof count); count = true; console.log(typeof count);
  • Puede realizar diferentes acciones para diferentes tipos de datos. Por ejemplo,
 let count = 4; if(typeof count === 'number') ( // perform some action ) else if (typeof count = 'boolean') ( // perform another action )

Articulos interesantes...