Determining if a Value is an Object in JavaScript
JavaScript's dynamic typing can sometimes make it tricky to determine the type of a variable. This challenge focuses on creating a function that accurately identifies whether a given value is a JavaScript object, excluding primitive types like strings, numbers, booleans, null, and undefined. This is a common task in data validation and type checking scenarios.
Problem Description
You are tasked with writing a JavaScript function called isObject that takes a single argument, value, and returns true if the value is a JavaScript object. An object, for the purpose of this challenge, is defined as a non-primitive type. Specifically, it should return true for objects created using new Object(), object literals ({}), and instances of custom classes. It should return false for primitive types (string, number, boolean, symbol, bigint), null, and undefined.
Key Requirements:
- The function must correctly identify objects.
- The function must correctly identify non-object values.
- The function should handle edge cases gracefully.
Expected Behavior:
The function should return a boolean value (true or false).
Edge Cases to Consider:
null: Should returnfalse.undefined: Should returnfalse.- Primitive types (string, number, boolean, symbol, bigint): Should return
false. - Empty object
{}: Should returntrue. - Instances of custom classes: Should return
true. - Arrays: Should return
true(Arrays are objects in JavaScript).
Examples
Example 1:
Input: { name: "Hone" }
Output: true
Explanation: The input is a standard JavaScript object literal.
Example 2:
Input: "hello"
Output: false
Explanation: The input is a string, which is a primitive type.
Example 3:
Input: null
Output: false
Explanation: null is not an object.
Example 4:
Input: 123
Output: false
Explanation: The input is a number, a primitive type.
Example 5:
Input: new Object()
Output: true
Explanation: The input is an object created using the Object constructor.
Example 6:
Input: []
Output: true
Explanation: Arrays are objects in Javascript.
Constraints
- The function must accept any JavaScript value as input.
- The function must return a boolean value.
- The function should be efficient and avoid unnecessary computations. While performance isn't a primary concern for this problem, avoid overly complex or inefficient solutions.
Notes
Consider using the typeof operator and checking for the object type. However, be mindful of the special case of null, which typeof incorrectly identifies as "object". You might also explore using Object.prototype.toString.call() for a more robust check. Remember that arrays are also objects in JavaScript.