Language: EN

javascript-determinar-el-tipo-de-una-variable

Determine the Type of a Variable in JavaScript

In JavaScript, you may sometimes need to identify the type of an object or variable at runtime.

JavaScript is a dynamically typed language, which means that the type of a variable is determined and can change during the execution of the program.

Due to this flexibility, it is not always straightforward to determine the exact type of a value. Let’s look at the different options 👇.

Methods to Determine the Type in JavaScript

There are various methods in JavaScript to identify the type of an object or variable. The choice of method depends on the use case (and the level of precision you need).

MethodUse CasesLimitations
typeofPrimitive values, functionsDoes not distinguish arrays from objects
instanceofPrototype relationshipsFails in multiple environments
Object.prototype.toStringSpecific typesVerbose, requires extra call
constructorClasses and custom objectsCan be overwritten
prototype.nameIdentify custom classesNot universal

Check Primitive Values with typeof

The typeof operator is the simplest and most common method to determine the type of a variable. It returns a string indicating the type of the evaluated value.

typeof value;

For example,

console.log(typeof 42);           // "number"
console.log(typeof "Hello");      // "string"
console.log(typeof true);         // "boolean"
console.log(typeof undefined);    // "undefined"
console.log(typeof null);         // "object" (historical quirk)
console.log(typeof {});           // "object"
console.log(typeof []);           // "object" (but it is an array)
console.log(typeof function(){}); // "function"
  • typeof is useful for primitive values (numbers, strings, booleans, etc.).
  • Identifies functions as function.
  • Does not distinguish between null, general objects ({}), and arrays ([]), which limits its utility in certain cases.

Check if it is an Instance of a Class with instanceof

The instanceof operator checks if an object is an instance of a class or if it inherits from its prototype.

object instanceof Class;

For example,

class Person {}
const juan = new Person();

console.log(juan instanceof Person); // true
console.log([] instanceof Array);     // true
console.log({} instanceof Object);    // true
  • Works only with objects, not with primitive values.
  • Useful for identifying custom classes or inheritance hierarchies.
  • Cannot detect the type of primitive values like string or number.

Caution:

If you are working with multiple environments (e.g., iframes), instanceof may fail because object prototypes in different contexts are different.

Identify Specific Types with Object.prototype

The Object.prototype.toString() method is a quite useful technique to determine the type of an object.

Syntax:

Object.prototype.toString.call(value);

This method will always return a string in the form of [object Type]. For example,

console.log(Object.prototype.toString.call(42));         // "[object Number]"
console.log(Object.prototype.toString.call("Hello"));     // "[object String]"
console.log(Object.prototype.toString.call([]));         // "[object Array]"
console.log(Object.prototype.toString.call({}));         // "[object Object]"
console.log(Object.prototype.toString.call(null));       // "[object Null]"
console.log(Object.prototype.toString.call(undefined));  // "[object Undefined]"
console.log(Object.prototype.toString.call(function(){})); // "[object Function]"
console.log(Object.prototype.toString.call(new Date())); // "[object Date]"
  • It is more reliable than typeof for distinguishing between objects, arrays, and null.
  • Commonly used to detect special types like Date, RegExp, or Error.

Check the Constructor with constructor

Another way is to use the constructor property of an object that references the constructor function that created it.

object.constructor;

This can be useful for identifying custom types. For example,

const date = new Date();
console.log(date.constructor === Date); // true

const myArray = [];
console.log(myArray.constructor === Array); // true
  • If the constructor property is overwritten, this method is not reliable.
  • Does not work with primitive values.

Identify the Prototype with prototype.name

Some prototypes (like those created with custom classes) have a name property that indicates their type.

This is useful when we want to identify between custom classes (like those created by ourselves). For example,

// here would go your class definition
class Vehicle { }

const car = new Vehicle();
console.log(car.constructor.name); // "Vehicle"
  • Works only with custom classes or explicitly defined constructors.

Combination of Methods

In practice, it may sometimes be necessary to combine multiple methods to identify types with greater precision.

For example, you can use typeof for primitive values and Object.prototype.toString for complex objects:

function getType(value) {
  if (typeof value === "object") {
    if (value === null) return "null";
    if (Array.isArray(value)) return "array";
    return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
  }
  return typeof value;
}

console.log(getType(42));           // "number"
console.log(getType("Hello"));      // "string"
console.log(getType([]));           // "array"
console.log(getType({}));           // "object"
console.log(getType(null));         // "null"
console.log(getType(undefined));    // "undefined"

Here,

  • First, we use typeof to determine if the object is primitive
  • We also manually handle null types
  • Finally, we use prototype to obtain the rest of the cases (slice(8, -1) removes [object and the last ] from the string)