w3resource

JavaScript: Get a boolean determining if the passed value is an object or not

JavaScript fundamental (ES6 Syntax): Exercise-194 with Solution

Check If Object

Write a JavaScript program to get a boolean determining if the passed value is an object or not.

  • Uses the Object constructor to create an object wrapper for the given value.
  • If the value is null or undefined, create and return an empty object.
  • Otherwise, return an object of a type that corresponds to the given value.

Sample Solution:

JavaScript Code:

// Define a function 'isObject' that checks if the given value 'obj' is an object
const isObject = obj =>
  // Check if 'obj' is strictly equal to Object(obj)
  obj === Object(obj);

// Test cases to check if the values are objects
console.log(isObject([1, 2, 3, 4]));  
console.log(isObject([]));             
console.log(isObject(['Hello!']));     
console.log(isObject({ a: 1 }));      
console.log(isObject({}));           
console.log(isObject(true)); 

Output:

true
true
true
true
true
false

Flowchart:

flowchart: Get a boolean determining if the passed value is an object or not

Live Demo:

See the Pen javascript-fundamental-exercise-194 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that returns true if a value is an object and not null.
  • Write a JavaScript function that checks whether an argument is a non-primitive object.
  • Write a JavaScript program that uses Object.prototype.toString() to verify that a variable is an object.
  • Write a JavaScript function that distinguishes objects from arrays, functions, and primitives.

Go to:


PREV : Check If Object-Like.
NEXT : Check If Number.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.