Skip to content
Home » JavaScript: Exploring different ways to find variable types

JavaScript: Exploring different ways to find variable types

In this blog post, we will be exploring different ways to find variable types in JavaScript, enabling you to write more robust and error-free code.

Introduction

  • In JavaScript, being a dynamically-typed language, variables can hold values of different types throughout their lifecycle.
  • It is often important to determine the type of variable to perform appropriate operations or make informed decisions.
  • In JavaScript, a dynamically-typed language, understanding the type of a variable is crucial for effective programming.
  • JavaScript provides several methods to determine the type of a variable.

Tabular format for easy reference

MethodExampleOutputPrecisionUsage
typeoftypeof num“number”GeneralQuick type identification for primitive types.
instanceoftoday instanceof DatetrueSpecificChecks if the object belongs to a specific class or constructor function.
Object.prototype.toString()Object.prototype.toString.call(person)“[object Object]”A quick and simple method to get a general idea of the variable’s type.Retrieves the object’s specific type.
Array.isArray()Array.isArray(fruits)trueSpecific (for arrays)Determines if a variable is an array.
Duck Typingif (data.length !== undefined && data.splice !== undefined)
console.log(“Array type”);
} else {
console.log(“Not an array”);
}
Array typeFocuses on an object’s behavior rather than its type.

Flexibility in object interchangeability based on behavior.

Let’s dive into the details of each method

typeof operator

  • It is the simplest and most common method to check the type of a variable in JavaScript.
  • It returns a string indicating the type of the variable.
  • The possible return values include “undefined,” “boolean,” “number,” “string,” “bigint,” “symbol,” “object,” and “function.”
  • Limitation: It returns the same value, “object,” for both null and arrays.
  • Use Case: The typeof operator is useful for quick type identification of primitive data types when you need a general understanding of the variable’s type.
TypeExampleResult
Undefinedtypeof undefined“undefined”
Nulltypeof null“object”
Booleantypeof true“boolean”
Numbertypeof 42“number”
BigInttypeof BigInt(10)“bigint”
Stringtypeof "Hello"“string”
Symboltypeof Symbol()“symbol”
Functiontypeof function() {}“function”
Objecttypeof {} or typeof []“object”

Example:

let name = "John";
console.log(typeof name); // Output: "string"

let num = 42;
console.log(typeof num);  // Output: "number"

let isAdmin = true;
console.log(typeof isAdmin); // Output: "boolean"

let calculate = function(a, b) {
  return a + b;
}
console.log(typeof calculate); // Output: "function"

let person = { name: "Alice", age: 25 };
console.log(typeof person); // Output: "object"


instanceof operator

  • It allows you to check whether an object belongs to a specific class or constructor function.
  • It evaluates to true if the object is an instance of the specified class or its subclasses; otherwise, it returns false.
  • It is particularly useful for complex data structures, identifying custom-defined types, and differentiating between objects and primitive types.
  • Use Case: The instanceof operator is beneficial when you want to determine if an object is derived from a specific class or constructor function, enabling you to handle objects based on their specific types and perform actions accordingly.

Example:

let person = new Person();
console.log(person instanceof Person); // Output: true

let today = new Date();
console.log(today instanceof Date);    // Output: true

let list = [1, 2, 3];
console.log(list instanceof Array);    // Output: true


Object.prototype.toString()

  • Every object in JavaScript inherits the toString() method from the Object.prototype.
  • This method can be used to obtain the object’s specific type.
  • can be used to find the internal [[Class]] property of an object.
  • Although it involves some additional steps, it provides more precise results compared to the typeof operator.
  • Use Case: The Object.prototype.toString() method is particularly useful when you need to differentiate between various object types and retrieve the exact type of an object.

Example:

let arr = [1, 2, 3];
console.log(Object.prototype.toString.call(arr)); // Output: "[object Array]"

let person = { name: "Alice" };
console.log(Object.prototype.toString.call(person));  // Output: "[object Object]"

let regex = /abc/;
console.log(Object.prototype.toString.call(regex));   // Output: "[object RegExp]"


Array.isArray()

  • As the name suggests, Array.isArray() is a built-in method that specifically checks whether a given value is an array.
  • It returns true if the value is an array; otherwise, it returns false.
  • This method is especially handy when differentiating arrays from other object types.
  • This method is reliable and more readable than other techniques because typeof returns “object” for arrays.
  • Use Case: The Array.isArray() method is valuable when you want to confirm if a variable is an array before performing specific array-related operations.

Example:

let arr = [1, 2, 3];
console.log(Array.isArray(arr)); // Output: true

let num = 42;
console.log(Array.isArray(num));      // Output: false


Duck typing

  • In JavaScript, duck typing is a technique that focuses on an object’s behavior rather than its type.
  • By checking for specific methods or properties, you can infer the type of an object.
  • For example, if an object has a length property and allows bracket notation, it is likely an array or a string.

Example:

let data = [1, 2, 3];

if (data.length !== undefined && data.splice !== undefined) {
  console.log("Array type");
} else {
  console.log("Not an array");
}


Conclusion

  • Knowing the type of a variable is crucial for writing reliable and error-free JavaScript code.
  • While the typeof operator is the most commonly used method, it has its limitations.
  • Other techniques like instanceof, Object.prototype.toString(), and Array.isArray() can provide more precise information about the variable’s type, particularly for objects and arrays.

By employing these different approaches, you can confidently handle variables of varying types in your JavaScript applications.


Visit Techtalkbook to find more related topics.


References

Leave a Reply

Your email address will not be published. Required fields are marked *

1 Shares
Tweet
Pin1
Share
Share
Share