Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: what does Object(variable)?

I ran into a boolean test variable === Object(variable) but couldn't find anything that describes it.

Is it testing that variable is the same as Object(variable) and does Object(variable) cast this variable into object? Or does it do something else?

If it matches it will loop for (var key in variable) and uses key and variable[key] as parameters for another function. If it fails it uses just that variable as is.

like image 650
user1271930 Avatar asked Feb 12 '26 05:02

user1271930


1 Answers

It checks that

  1. the variable is defined
  2. its value is an object
  3. its value isn't null (be careful: typeof null is "object")

This is probably the simplest way to check these 3 conditions and it looks like a reasonable test to run before to loop on keys in a very polymorphic function.

Another one would have been typeof variable === "object" && variable.

From the MDN:

The Object constructor creates an object wrapper for the given value. If the value is null or undefined, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.

like image 187
Denys Séguret Avatar answered Feb 13 '26 17:02

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!