Hone logo
Hone
Problems

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 true if the argument is a plain object.
  • It should return false otherwise.

Expected Behavior:

  • {} should return true.
  • new Object() should return true.
  • { a: 1 } should return true.
  • [] (an array) should return false.
  • new Date() should return false.
  • null should return false.
  • undefined should return false.
  • 123 (a number) should return false.
  • "hello" (a string) should return false.
  • true (a boolean) should return false.
  • function() {} should return false.
  • Instances of custom classes (e.g., class Person {}; new Person()) should return false.

Edge Cases to Consider:

  • The behavior with null is particularly important, as typeof null in JavaScript returns "object". Your function must correctly identify null as 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.

Loading editor...
javascript