Immerse

Immerse

github
email
twitter
youtube
zhihu

Stop being fooled! Best practices for JavaScript type checking

Don't be fooled anymore! Best Practices for JavaScript Type Checking#

In JavaScript, we often need to determine the type of a variable. This requirement is very common in programming because different types of data can affect our code logic.

JavaScript provides several methods to detect data types, each with its own advantages and disadvantages.

Object.prototype.toString.call()#

This is the most versatile method. It can accurately identify all JavaScript built-in types, including primitive types and complex types. No matter what data you pass to it, it can give you a unified format string that tells you what type of data it is.

Its principle is to call the [[Class]] property inside the object. This property is read-only and cannot be rewritten, so it is very reliable.

Advantages:

  • Wide range of recognition, can recognize both primitive types and complex types
  • Not affected by the object's own toString() method
  • Returns results in a unified format for easy parsing

Disadvantages:

  • More verbose to write
  • If it is a custom type, it can only get [object Object] and cannot further distinguish the type
function detectType(data) {
    return Object.prototype.toString.call(data).slice(8, -1).toLowerCase();
}

console.log(detectType(123)); // 'number'
console.log(detectType('abc')); // 'string'
console.log(detectType(true)); // 'boolean'
console.log(detectType(null)); // 'null'
console.log(detectType(undefined)); // 'undefined'
console.log(detectType([])); // 'array'
console.log(detectType({})); // 'object'
console.log(detectType(function () {})); // 'function'
console.log(detectType(new Date())); // 'date'
console.log(detectType(new RegExp())); // 'regexp'
console.log(detectType(new Error())); // 'error'

typeof#

This operator is the most commonly used and simple to write. It can identify primitive types and functions, but has limited recognition capabilities for complex types.

Advantages:

  • Simple to use
  • Can identify primitive types and functions

Disadvantages:

  • Cannot distinguish between arrays and plain objects
  • The result of typeof null is 'object'
  • Cannot recognize built-in object types such as Date and RegExp
console.log(typeof 123); // 'number'
console.log(typeof 'abc'); // 'string'
console.log(typeof true); // 'boolean'
console.log(typeof undefined); // 'undefined'
console.log(typeof null); // 'object' (this is a historical bug)
console.log(typeof []); // 'object'
console.log(typeof {}); // 'object'
console.log(typeof function () {}); // 'function'

instanceof#

The instanceof operator is used to test whether the prototype property of a constructor appears anywhere in the prototype chain of an object.

Advantages:

  • Can check if an object belongs to a specific class or constructor

Disadvantages:

  • Can only check object types, not primitive types
  • Multiple calls are required to identify multiple types
console.log([] instanceof Array); // true
console.log({} instanceof Object); // true
console.log(function () {} instanceof Function); // true
console.log(new Date() instanceof Date); // true
console.log(new RegExp() instanceof RegExp); // true
console.log(new Error() instanceof Error); // true

console.log(123 instanceof Number); // false
console.log('abc' instanceof String); // false
console.log(true instanceof Boolean); // false

constructor#

constructor is a property of an object that points to the constructor function that created the object. It can be used to determine the type of an object.

Advantages:

  • Can identify most object types, including custom types

Disadvantages:

  • If the constructor property of an object is modified, incorrect results may be obtained
  • null and undefined do not have a constructor property
console.log((123).constructor === Number); // true
console.log('abc'.constructor === String); // true
console.log(true.constructor === Boolean); // true
console.log([].constructor === Array); // true
console.log({}.constructor === Object); // true
console.log(function () {}.constructor === Function); // true
console.log(new Date().constructor === Date); // true
console.log(new RegExp().constructor === RegExp); // true
console.log(new Error().constructor === Error); // true

Summary#

If you need comprehensive and accurate type identification, Object.prototype.toString.call() is the best choice.
If you only need to differentiate primitive types, typeof is sufficient.
If you want to check if an object belongs to a specific type, you can use instanceof.

In practical applications, we can choose the appropriate method based on specific requirements.

Conclusion#

Last time, I developed a tool that can clean up unused repositories in batches. If you are interested, you can take a look! 😊

Introduction Article: https://mp.weixin.qq.com/s/t7lgc6b7xJiNhfm5vWo5-A

GitHub Repository: https://github.com/yaolifeng0629/del-repos

If you find this tool helpful, please don't forget to give my GitHub repository a Star ⭐! Your support is my motivation to move forward!

Thank you for reading, see you next time!

image

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.