tipo de JavaScript


Tabla de contenido

    Mostrar tabla de contenidos


En JavaScript existen 5 tipos de datos diferentes que pueden contener valores:

  • cadena

  • número

  • booleano

  • objeto

  • función

Hay 6 tipos de objetos:

  • Objeto

  • Fecha

  • Matriz

  • Cadena

  • Número

  • Booleano

Y 2 tipos de datos que no pueden contener valores:

  • nulo

  • indefinido


El tipo de operador

Puede utilizar el operador typeof para encontrar el tipo de datos de un variables de javascript.

Ejemplo

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 {name:'John', age:34} 
// Returns "object"
typeof new Date()             
// Returns "object"
typeof function () {}         // Returns 
 "function"
typeof myCar                  
// Returns "undefined" *
typeof null                   
// Returns "object"

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The typeof Operator</h2>

<p>The typeof operator returns the type of a variable, object, function or expression:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
"'John' is " + typeof "John" + "<br>" +
"3.14 is " + typeof 3.14 + "<br>" +
"NaN is " + typeof NaN + "<br>" +
"false is " + typeof false + "<br>" +
"[1, 2, 3, 4] is " + typeof [1, 2, 3, 4] + "<br>" +
"{name:'John', age:34} is " + typeof {name:'John', age:34} + "<br>" +
"new Date() is " + typeof new Date() + "<br>" +
"function () {} is " + typeof function () {} + "<br>" +
"myCar is " + typeof myCar + "<br>" +
"null is " + typeof null;
</script>

</body>
</html>

Por favor observe:

  • El tipo de datos de NaN es número

  • El tipo de datos de una matriz es objeto.

  • El tipo de datos de una fecha es objeto.

  • El tipo de datos de nulo es objeto.

  • El tipo de datos de una variable indefinida es indefinido *

  • El tipo de datos de una variable a la que no se le ha asignado un valor es también indefinido *

No puede utilizar typeof para determinar si un objeto JavaScript es una matriz (o una fecha).



Datos primitivos

Un valor de datos primitivo es un valor de datos simple y único sin ningún valor adicional. propiedades y métodos.

El operador typeof puede devolver uno de estos tipos primitivos:

  • cadena

  • número

  • booleano

  • indefinido

Ejemplo

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)

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The typeof Operator</h2>
<p>The typeof operator returns the type of a variable or an expression.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
typeof "john" + "<br>" + 
typeof 3.14 + "<br>" +
typeof true + "<br>" +
typeof false + "<br>" +
typeof x;
</script>

</body>
</html>



Datos complejos

El operador typeof puede devolver uno de dos tipos complejos:

  • función

  • objeto

El operador typeof devuelve "objeto" para objetos, matrices y nulos.

El operador typeof no devuelve "objeto" para funciones.

Ejemplo

typeof {name:'John', age:34} // Returns "object"
typeof [1,2,3,4]            
// Returns "object" (not "array", see note below)
typeof null                  // Returns 
  "object"
typeof function myFunc(){}   // Returns "function"

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The typeof Operator</h2>
<p>The typeof operator returns object for both objects, arrays, and null.</p>
<p>The typeof operator does not return object for functions.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
typeof {name:'john', age:34} + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof null + "<br>" +
typeof function myFunc(){};
</script>

</body>
</html>


El operador typeof devuelve "objeto" para matrices porque en JavaScript las matrices son objetos.


El tipo de datos de typeof

El operador typeofno es una variable. Es un operador. Operadores ( + - * / ) no tienen ningún tipo de datos.

Pero el operador typeof siempre devuelve una cadena (que contiene el tipo de operando).


La propiedad del constructor

La propiedad constructor devuelve el constructor función para todas las variables de JavaScript.

Ejemplo

"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]}
{name:'John',age:34}.constructor 
// Returns function Object()  {[native code]}
 new Date().constructor           
// Returns function Date()    {[native code]}
function () {}.constructor        // Returns 
  function Function(){[native code]}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Properties</h1>
<h2>The constructor Property</h2>

<p>The constructor property returns the constructor function for a variable or an 
object.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
  "john".constructor + "<br>" +
  (3.14).constructor + "<br>" +
  false.constructor + "<br>" +
  [1,2,3,4].constructor + "<br>" +
  {name:'john', age:34}.constructor + "<br>" +
  new Date().constructor + "<br>" +
  function () {}.constructor;
</script>

</body>
</html>


Puede comprobar la propiedad del constructor para saber si un objeto es una matriz (contiene la palabra "Matriz"):

Ejemplo

function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

<p>This &quot;home made&quot; isArray() function returns true when used on an array:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple"];
document.getElementById("demo").innerHTML = isArray(fruits);

function isArray(myArray) {
  return myArray.constructor.toString().indexOf("Array") > -1;
}
</script>

</body>
</html>

O incluso más simple, puedes verificar si el objeto es una función de matriz:

Ejemplo

function isArray(myArray) {
    return myArray.constructor 
  === Array;
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Array Object</h1>
<p>This "home made" isArray() function returns true when used on an array:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = isArray(fruits);

function isArray(myArray) {
  return myArray.constructor === Array;
}
</script>

</body>
</html>

Puede comprobar la propiedad del constructor para saber si un objeto es un Fecha (contiene la palabra "Fecha"):

Ejemplo

function isDate(myDate) {
    return myDate.constructor.toString().indexOf("Date") > -1;
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Date Object</h2>
<p>This "home made" isDate() function returns true when used on an date:</p>

<p id="demo"></p>

<script>
const myDate = new Date();
document.getElementById("demo").innerHTML = isDate(myDate);

function isDate(myDate) {
  return myDate.constructor.toString().indexOf("Date") > -1;
}
</script>

</body>
</html>

O incluso más simple, puedes verificar si el objeto es una función de fecha:

Ejemplo

function isDate(myDate) {
    return myDate.constructor === Date;
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Date Object</h2>
<p>This "home made" isDate() function returns true when used on an date:</p>

<p id="demo"></p>

<script>
const myDate = new Date();
document.getElementById("demo").innerHTML = isDate(myDate);

function isDate(myDate) {
  return myDate.constructor === Date;
}
</script>

</body>
</html>

Indefinido

En JavaScript, una variable sin valor tiene el valor undefinido. El tipo también es undefinido.

Ejemplo

let car;    // Value is undefined, 
    type is undefined

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The typeof Operator</h2>
<p>The value (and the data type) of a variable with no value is <b>undefined</b>.</p>

<p id="demo"></p>

<script>
let car;
document.getElementById("demo").innerHTML =
car + "<br>" + typeof car;
</script>

</body>
</html> 

Cualquier variable se puede vaciar estableciendo el valor en undefinido. El tipo también será undefinido.

Ejemplo

   car = undefined;    // Value is undefined, 
    type is undefined

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The typeof Operator</h2>
<p>Variables can be emptied if you set the value to <b>undefined</b>.</p>

<p id="demo"></p>

<script>
let car = "Volvo";
car = undefined;

document.getElementById("demo").innerHTML = car + "<br>" + typeof car;
</script>

</body>
</html> 

Valores vacíos

Un valor vacío no tiene nada que ver con undefinido.

Una cadena vacía tiene tanto un valor legal como un tipo.

Ejemplo

let car = "";    // 
    The value is 
    "", the typeof is "string"

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript</h2>

<p>An empty string has both a legal value and a type:</p>

<p id="demo"></p>

<script>
let car = "";
document.getElementById("demo").innerHTML =
"The value is: " +
car + "<br>" +
"The type is: " + typeof car;
</script>

</body>
</html>



Nulo

En JavaScript null es "nada". Se supone que es algo que no existe.

Desafortunadamente, en JavaScript, el tipo de datos de null es un objeto.

Puede considerar un error en JavaScript que typeof null sea un objeto. Debería ser nulo.

Puede vaciar un objeto configurándolo en null:

Ejemplo

let person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = null;    // 
  Now value is null, 
    but type is still an object

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript</h2>

<p>Objects can be emptied by setting the value to <b>null</b>.</p>

<p id="demo"></p>

<script>
let person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = null;
document.getElementById("demo").innerHTML = typeof person;
</script>

</body>
</html> 

También puedes vaciar un objeto configurándolo en undefinido:

Ejemplo

let person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = undefined;   // 
  Now both value and type is undefined

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Objects</h1>
<h2>The undefined Data Type</h2>

<p>Objects can be emptied by setting the value to <b>undefined</b>.</p>

<p id="demo"></p>

<script>
let person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = undefined;
document.getElementById("demo").innerHTML = person;
</script>

</body>
</html> 

Diferencia entre indefinido y nulo

undefinido y null son iguales en valor pero diferentes en tipo:

typeof undefined           
    // undefined
typeof null                
    // object
null === undefined         
    // false
null == undefined          
    // true

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The typeof Operator</h2>
<p>Undefined and null are equal in value but different in type:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
typeof undefined + "<br>" +
typeof null + "<br><br>" +
(null === undefined) + "<br>" +
(null == undefined);
</script>

</body>
</html> 

La instancia del operador

El operador instanceof devuelve true si un objeto es una instancia del objeto especificado:

Ejemplo

const cars = ["Saab", "Volvo", "BMW"];

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

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The instanceof Operator</h2>

<p>The instanceof operator returns true if an object is an instance of a specified object:</p>

<p id="demo"></p>

<script> 
const cars = ["Saab", "Volvo", "BMW"];

document.getElementById("demo").innerHTML =
(cars instanceof Array) + "<br>" + 
(cars instanceof Object) + "<br>" +
(cars instanceof String) + "<br>" +
(cars instanceof Number);
</script>

</body>
</html>

El operador vacío

El operador void evalúa una expresión y devuelve indefinido. Este operador se utiliza a menudo para obtener el valor indefinido. valor primitivo, usando "void(0)" (útil al evaluar una expresión sin utilizando el valor de retorno).

Ejemplo

<a href="javascript:void(0);">
  Useless link
</a>
 
<a href="javascript:void(document.body.style.backgroundColor='red');">
  Click me to change the background color of body to red
</a>

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The void Operator</h2>

<p>
<a href="javascript:void(0);">Useless link</a>
</p>

<p>
<a href="javascript:void(document.body.style.backgroundColor='red');">
Click me to change the background color of body to red.</a>
</p>

</body>
</html>