Welcome to Shorat Programming! Learn, Code, and Get Certified with Shorat Programming.
How to Check Type in JavaScript
JavaScript is a language that allows us to assign values to the variables at the run time. In the same
way, the
ability to determine variable types and value types becomes significant when programming. However,
numerous ways
of handling this in JavaScript can guarantee a variable is of a certain type or has a defined value. In
the
present article, we will explore them and provide you with relevant examples and explanations through
the
research paper.
Implementation of the typeof Operator:
The type of operand is revealed by the string that typeof operator gives back as its returned value.
Knowing the
exact value or variable is the best way for you to learn this.
let x = 5;
let y = "Hello";
let z = true;
console.log(typeof x);
console.log(typeof y);
console.log(typeof z);
Output
"number"
"string"
"boolean"
For typeof x equals "number" is that x has a value that is assigned to it as a number
With y being a string type, typeof y returns "string."
Since z is a boolean variable, the function typeof z will result in "boolean".
Using the instanceof Operator:
Operators class has much more to offer as it not only provides Operator as an operator but also Operator
instance.
The instanceof operator is used to check if an object belongs to a particular class or not. It categorizes the
items in an object is identified as either of a certain class or its subclasses.
let arr = [1, 2, 3];
let obj = { name: "John", age: 30 };
console.log(arr instanceof Array);
console.log(obj instanceof Object);
This is because arr is an instance of the Array class; thus, the instanceof Array evaluates to true.
Because obj belongs to the Object class, obj instanceof Object gives true as a result
Using isArray() in Array:
The function Array.isArray() is used to check whether the value passed is an array or not.
let arr = [1, 2, 3];
let obj = { name: "John", age: 30 };
console.log(Array.isArray(arr)); // Output: true
console.log(Array.isArray(obj)); // Output: false
As arr is an array, Array.isArray(arr) returns the value true.
The method Array.isArray(obj) is not applicable here because obj is not an array, so it returns false
Applying .call() to Object.prototype.toString:
This approach will be a more dependable method to recognize the nature of an object.
let num = 5;
let str = "Hello";
let bool = true;
let func = function() {};
let arr = [1, 2, 3];
let obj = { name: "John", age: 30 };
console.log(Object.prototype.toString.call(num));
console.log(Object.prototype.toString.call(str));
console.log(Object.prototype.toString.call(bool));
console.log(Object.prototype.toString.call(func));
console.log(Object.prototype.toString.call(arr));
console.log(Object.prototype.toString.call(obj));
Output
[object Number]
[object String]
[object Boolean]
[object Function]
[object Array]
[object Object]
Explaination:
The function Object.prototype.toString.call(value) will return the object's value. Creating a working code that
does not have any errors but rather is correct is a function of knowing how to express the types of variables or
values in JavaScript.
Developers can now be able to accurately find the type of variables or values in their JavaScript applications
by employing methods like typeof, instanceof, Array.isArray(), and Object.prototype.toString.call(). It ensures
that there will be no risk of mistakes and incorrect manipulation.
Employing typeof with Functions and Null
It's important to remember that typeof behaves strangely sometimes when working with certain types, such as
functions and null.
Example: There is a known contradiction in JavaScript where typeof nullValue returns "object" rather than
"null".
The function type of the variable func is shown by the return value "function" from typeof function
Checking for NaN with isNaN()
JavaScript may return NaN (Not a Number) when working with numeric numbers, especially when performing operations
like division by zero or improper mathematical operations. The isNaN() method can be used to check for NaN.
let result1 = 10 / 0;
let result2 = "Hello" / 5;
console.log(isNaN(result1)); // Output: false
console.log(isNaN(result2)); // Output: true
Explanation:
Since result1 is Infinity, which is regarded as a numeric number, isNaN(result1) returns
false.
Since dividing a string by a number is an improper operation, isNaN(result2) returns true since result2 is NaN.
Knowing the types of JavaScript methods for type checking used by developers makes them powerful enough to make sure
their code runs as expected. Being able to use typeof for basic type checking, instanceof for object type checking,
and Array.isArray() for arrays will be useful for developers to build more reliable and reusable JavaScript
programs.
Besides, having the detailed and odd features - like typeof null returns "object" or use isNaN() to manage NaN -
gives us the ability to navigate the more skillfully and fluently the type system. Developers may avoid errors and
contribute to better code integrity by following the suggested techniques and employing them in their coding
practices.
Using typeof for undefined Variables:
JavaScript is to say "undefined" when the typeof operator is applied to variables that are not yet declared or
initialized. First of all, this will help in the process of declaring whether a variable has been defined or set
to a value.
let x;
let y;
console.log(typeof x); // Output: "undefined"
console.log(typeof y); // Output: "undefined"
Reason: As x and y are both declared but not defined, typeof returns "undefined" for both of them.
Object Property Checking:
In some cases, you may be excused from asking whether an item has a specific quality. You can do this with the
help of the hasOwnProperty() function or the in operator.
For instance:
Let person = { name: "Alice," age: 30 };
console.log("name" in person); // Output: true
console.log("gender" in person); // Output: false
console.log(person.hasOwnProperty("name")); // Output: true
console.log(person.hasOwnProperty("gender")); // Output: false
Justification: A person's "name" will be assigned to a person object if the "name" attribute is available.
"gender" in the "person" is the object that helps to identify the "gender" property.
The statement "person.hasOwnProperty("name")" checks if the object "person" has its property as well.
Whether the person object's "gender" property is set or not is tested by checking the presence of a
person.hasOwnProperty("gender").
Subdividing Function and Object with typeof:
However, typeof does not distinguish standard objects and functions; it does return a value "function" for
functions. You may also use typeof to underline whether a value is a function and then perform a series of tests
to differentiate it from other kinds of objects
function greet() {
console.log("Hello!");
}
Let person = { name: "Bob," age: 25 };
console.log(typeof greet === "function");
console.log(typeof person === "function");
This is because since welcome is a function, typeof greet === "function" yields true.
A person is not a function, so typeof person === "function" yields false.
Conclusion
Writing dependable code in JavaScript requires an understanding of type-checking. To reliably establish types,
JavaScript has several techniques, including typeof, instanceof, and object property checks. These may be used
with primitive types, objects, or functions. By utilizing these strategies efficiently, developers may build
cleaner, more maintainable code that handles various data types correctly. This improves developer productivity
and software quality.