Difference between typeof and instanceof #
While typeof is mostly associated with primitive types, it can also check some non-primitive types in a general way. On the other hand, instanceof is specifically used for non-primitive types.
typeof: This operator is mainly used to check the type of primitive data types, but it can also be used on non-primitive types. For example, typeof returns “object” for objects (including arrays and null) and “function” for functions. However, it doesn’t distinguish between different object types (e.g., it can’t tell the difference between an array and an object).
instanceof: This operator is specifically used to check if an object is an instance of a particular class or constructor function, which makes it ideal for checking non-primitive types. It doesn’t work with primitive types like string, number, or boolean.
In addition to understanding typeof and instanceof, it’s important to know special numeric values like NaN. Let’s explore what NaN is and how it behaves in JavaScript.
What is the NaN property in JavaScript?#
NaN is used to signify a value that is not a valid number, often resulting from mathematical operations that don’t produce a meaningful numeric result. Understanding and correctly handling NaN is important for robust error handling and debugging in JavaScript. Following are some key points about NaN:
Type: NaN is of type number. Despite its name, it’s technically a numeric value.
Usage: It commonly appears in scenarios such as dividing zero by zero or attempting to convert a non-numeric string to a number.
Note: A unique feature of NaN is that it is not equal to itself. This means that NaN === NaN is false.
Here’s another important tip for using NaN:
Tip: To check if a value is NaN, use the Number.isNaN() method rather than the global isNaN() function, which has some quirks. The Number.isNaN() method accurately determines whether a value is NaN and not any non-numeric value.
Let’s consider the following code example to see how NaN works. Feel free to press the “Run” button to see the output: