What is a potential pitfall using typeof bar === “object” to determine if bar is an object ?
Last Updated :
13 Jan, 2023
The typeof operator in JavaScript returns a string that indicates the data type of the operand, whether it be a variable, function, or object.
Syntax: Following is the syntax of typeof operator:
typeof operand
// OR
typeof(operand)
Parameter: It takes the following parameter:
- operand: The expression whose type needs to be evaluated.
Example: Basic example demonstrating the typeof operator.
Javascript
<script>
console.log( typeof "Geeks" );
console.log( typeof 1);
console.log( typeof false );
console.log( typeof geeksForGeeks);
console.log( typeof { name: "Rajat" , gender: "Male" });
</script>
|
Output:
string
number
boolean
undefined
object
An object in JavaScript is a collection of properties and these properties usually come in the form of key-value pairs. It can be considered as a non-primitive data type.
There are three different methods to create an object:
- By an object literal
- By using any object constructor
- By creating an instance of Object class in JavaScript directly.
Example: Create an object by an object literal.
Syntax:
const object = {property1: value1, property2: value2};
Javascript
<script>
const gfgObject = {
name: "Rajat" ,
age: 30,
gender: "Male"
};
console.log(gfgObject);
</script>
|
Output:
{
name: 'Rajat',
age: 30,
gender: 'Male'
}
Example: Create an object by using any object constructor
Javascript
<script>
function student(name, age, gender){
this .name = name;
this .age = age;
this .gender = gender;
}
const s = new student( "Rajat" ,11, "Male" );
console.log(s);
<script>
|
Output:
{
name: 'Rajat',
age: 11,
gender: 'Male'
}
Example: Create an object by creating an instance of Object class in JavaScript directly.
Syntax:
const GFG = new Object();
Javascript
const GFG = new Object();
GFG.name = "Rajat" ;
GFG.age = 35;
GFG.gender = "Male" ;
console.log(GFG);
|
Output:
{
name: 'Rajat',
age: 35,
gender: 'Male'
}
Coming to typeof bar === “object”, if the variable bar is an object meaning that if it takes the form of any of the three aforementioned object types, then the statement will return true. Initially, typeof bar === “object” seems like a reliable method to determine whether bar is an object or not. However, one potential pitfall of using the same is that in the realm of JavaScript, even the primitive value null is considered as an object.
This is actually a bug in the language since null should indicate the intentional absence of an object value yet it returns “object” when tested with the typeof operator. There was an attempt made to fix it in the past but it was rejected due to a backward compatibility issue. The following code snippet illustrates this issue:
Javascript
<script>
const bar = null ;
console.log( typeof bar === 'object' );
</script>
|
Output:
true
This can be avoided if a simple check is added to the pre-existing code. That is, check if bar !== null. Now it will yield the expected output (false).
Javascript
const bar = null ;
console.log((bar !== null ) && ( typeof bar === 'object' ));
|
Output:
false
Till this stage, it is assumed that bar is a variable. But what if bar is a function? The solution above will return false which is the desired output in most cases but if there is a scenario in which the expected output is true, the code needs to slightly modified as follows:
Javascript
<script>
function bar() {
const b = 1;
}
console.log((bar !== null ) && ( typeof bar === 'object' ) ||
( typeof bar === 'function' ));
</script>
|
Output:
true
If bar is an array, then the solution above will return true which is the desired output in this case since arrays are considered objects but if there is a situation where the output is expected to be false, the code can be amended as shown below:
Javascript
<script>
const bar = [1, 2, 3];
console.log((bar !== null ) && ( typeof bar === "object" ) &&
(toString.call(bar) !== "[object Array]" ));
</script>
|
Output:
false
There is one final alternative that returns false for arrays, nulls, and functions, but true for objects. The code looks as follows:
Javascript
<script>
const bar = { firstName: "foo" , lastName: "bar" };
console.log((bar !== null ) && (bar.constructor === Object));
</script>
|
Output:
true
Similar Reads
How to throw an error when using a property of an object ?
In this article, we will try to understand how we may throw an error when using a property of an object with the help of certain theoretical explanations as well as coding examples in JavaScript. Let us first have a look over the below section which shows the syntax for creating an object having cer
4 min read
How to Determine the type of an object in Ruby?
In this article, we will discuss how to determine the type of an object in Ruby. We can determine the type of an object through different methods ranging from using class method and is_a? method to instance_of? method. Table of Content Determining the type of an object using class methodDetermining
2 min read
How to get Function Parameters from Keys in an Array of Objects Using TypeScript ?
In TypeScript, we can extract the function parameters from keys in an array of objects by going through object properties dynamically. We can use Generics and Type Assertion to get Function Parameters from Keys in an Array of Objects Using TypeScript. Below are the possible approaches: Table of Cont
3 min read
How to use array that include and check an object against a property of an object ?
Array.includes() Method: In JavaScript, includes() method is used to determine that a particular element is present in an array or not. It returns true if the element is present and false when it is absent. Syntax: array_name.includes(searchElement, ?fromIndex) Parameters: searchElement: The element
3 min read
How to Narrow a Type of Derived Class Instances while Processing an Array ?
When it comes to JavaScript arrays that contain derived class instances, narrowing down the types is a must to access the specific functions or properties that are unique to those derived classes. Narrowing encompasses an act of specifically type-checking and casting objects explicitly to their deri
2 min read
How to compare two objects to determine the first object contains equivalent property values to the second object in JavaScript ?
In this article, we are going to learn about comparing two objects to determine if the first object contains equivalent property values to the second object, In JavaScript, comparing the values of two objects involves checking if they have the same properties with corresponding values. Given two obj
6 min read
Different Ways to Find the Type of an Object in Golang
Go does not have the concept of a class type, therefore, you do not have objects in Go. You can refer any data type in Go as an object. There are several data types provided by Go such as int8, int16, int32, int64, float64, string, bool etc. There are three different ways by which you can find the t
4 min read
How Check if object value exists not add a new object to array using JavaScript ?
In this tutorial, we need to check whether an object exists within a JavaScript array of objects and if they are not present then we need to add a new object to the array. We can say, every variable is an object, in Javascript. For example, if we have an array of objects like the following. obj = {
3 min read
How to Define Strongly Type Nested Object Keys with Generics in TypeScript ?
We will look into the effective use of generics in TypeScript to ensure type safety when working with nested objects. By employing generics, developers can establish strongly typed keys for nested objects, significantly reducing the likelihood of runtime errors and enhancing code maintainability. Ta
2 min read
How to Check if an Array Includes an Object in TypeScript ?
In TypeScript, checking if an array includes an object consists of comparing the object's properties within the array elements. We can compare and check this using three different approaches some method, find method, and includes method. There are several ways to check if an array includes an object
3 min read