Location>code7788 >text

Don't Get Pitted Again! Best Practices for JavaScript Type Detection

Popularity:396 ℃/2024-08-16 15:46:36

Don't Get Pitted Again! Best Practices for JavaScript Type Detection

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

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

()

This is the most versatile method. It recognizes all of JavaScript's built-in types, both basic and complex. No matter what data you pass it, it will give you a uniformly formatted string that tells you exactly what type the data is.

It works by calling the object's internal[[Class]] attribute. This attribute is read-only and cannot be overwritten, so it is very reliable.

Pros.

  • Recognizes a wide range of basic and complex types.
  • will not be affected by the object's owntoString() Impact of the methodology
  • Return results in a uniform format, easy to parse

Disadvantages.

  • It's a bit wordy.
  • If it is a custom type, you can only get[object Object], cannot further differentiate between types
function detectType(data) {
    return (data).slice(8, -1).toLowerCase();
}

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

typeof

This operator is the most commonly used and is simple to write. It recognizes basic types and functions, but has limited ability to recognize complex types.

Pros.

  • Simple to use
  • Can recognize basic types and functions

Disadvantages.

  • Cannot distinguish between arrays and normal objects
  • typeof null The result of the'object'
  • Unable to recognize built-in object types such asDateRegExp et al. (and other authors)
(typeof 123); // 'number'
(typeof 'abc'); // 'string'
(typeof true); // 'boolean'
(typeof undefined); // 'undefined'
(typeof null); // 'object' (It's a historical legacy of bug)
(typeof []); // 'object'
(typeof {}); // 'object'
(typeof function () {}); // 'function'

instanceof

instanceof operator is used to test the constructor'sprototype Whether the attribute appears anywhere in the object's prototype chain.

Pros.

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

Disadvantages.

  • Only object types can be checked, not basic types.
  • Multiple calls are required to recognize multiple types.
([] instanceof Array); // true
({} instanceof Object); // true
(function () {} instanceof Function); // true
(new Date() instanceof Date); // true
(new RegExp() instanceof RegExp); // true
(new Error() instanceof Error); // true

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

constructor

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

Pros.

  • Recognizes most object types, including custom types.

Disadvantages.

  • If the object'sconstructor attribute has been modified, you will get an error.
  • null cap (a poem)undefined hasn'tconstructor causality
((123).constructor === Number); // true
('abc'.constructor === String); // true
( === Boolean); // true
([].constructor === Array); // true
({}.constructor === Object); // true
(function () {}.constructor === Function); // true
(new Date().constructor === Date); // true
(new RegExp().constructor === RegExp); // true
(new Error().constructor === Error); // true

summarize

If full and accurate type identification is required.() It is the best choice.
If only a simple distinction between basic types is needed, thetypeof That's enough.
If you want to check whether an object is of a particular type, you can use theinstanceof

In practice, we can choose the appropriate method according to the specific needs.

concluding remarks

Last time I developed a tool to batch clean useless repositories. If you are interested, you can check it out oh! 😊

Introductory article/s/t7lgc6b7xJiNhfm5vWo5-A

GitHub repository address/yaolife ng0629/del-repos

If you found this tool helpful, please don't forget to contribute to my GitHub repository!Order a Star. ⭐! Your support is what keeps me going!

Thanks for reading and we'll see you next time!