Javascript: Is It An Object?
In JavaScript, distinguishing between different data types is crucial for writing robust and predictable code. One common task is to determine if a given value is a plain object. This skill is fundamental for tasks like configuration parsing, data manipulation, and working with APIs.
Problem Description
Your challenge is to create a JavaScript function that accurately checks if a given value is a plain JavaScript object. A "plain" object typically refers to an object created using curly braces {} or the new Object() constructor, and not instances of specific classes (like Arrays, Dates, or custom classes).
Key Requirements:
- The function should accept a single argument of any JavaScript type.
- It should return
trueif the argument is a plain object. - It should return
falseotherwise.
Expected Behavior:
{}should returntrue.new Object()should returntrue.{ a: 1 }should returntrue.[](an array) should returnfalse.new Date()should returnfalse.nullshould returnfalse.undefinedshould returnfalse.123(a number) should returnfalse."hello"(a string) should returnfalse.true(a boolean) should returnfalse.function() {}should returnfalse.- Instances of custom classes (e.g.,
class Person {}; new Person()) should returnfalse.
Edge Cases to Consider:
- The behavior with
nullis particularly important, astypeof nullin JavaScript returns"object". Your function must correctly identifynullas not a plain object. - Distinguishing between plain objects and arrays, dates, regular expressions, and other built-in object types.
Examples
Example 1:
Input: {}
Output: true
Explanation: An empty object literal is a plain object.
Example 2:
Input: [1, 2, 3]
Output: false
Explanation: Arrays are objects, but not considered "plain" objects for this purpose.
Example 3:
Input: null
Output: false
Explanation: While `typeof null` is 'object', it is not a plain object.
Example 4:
Input: new Date()
Output: false
Explanation: A Date object is an instance of the Date class, not a plain object.
Constraints
- The function should be implemented in JavaScript.
- The function should be efficient and not rely on excessively complex or slow operations.
- The input can be of any valid JavaScript data type.
Notes
Consider how the typeof operator behaves in JavaScript, and how you might augment its results to achieve the desired outcome. Remember that typeof [] also returns "object", so a simple typeof value === 'object' is insufficient. You may need to check additional properties or use constructor checks.