5

I just happened to notice that when assigning a variable as an Object, the typeof the variable is a 'function' whereas if I assign it as an empty object using object literal notation {} or instantiate as a new Object, the typeof variable is an object. What's the difference here?

Please note, I'm not asking the difference between Object literal notation and constructor notation.

enter image description here

Ramesh N
  • 185
  • 9

4 Answers4

7

The global symbol Object refers to the Object constructor function. Assigning Object to a variable just makes a copy of that reference, and is completely different from assigning a reference to a new empty object ({}).

Perhaps you're thinking of:

var a = new Object();
var b = {};

Those two statements do the same thing.

Pointy
  • 405,095
  • 59
  • 585
  • 614
4

When you assign a variable as an Object it references the Object function onto it whereas when you do new Object or {} it just creates a plain object with the constructor method of it's parent Object

You can understand more with screenshots

enter image description here

enter image description here enter image description here

Manzur Khan
  • 2,366
  • 4
  • 23
  • 44
2

a = Object; doesn't create a new object. It assigns the constructor function to your variable a. To create a new object, use this code: a = new Object();

JSON Derulo
  • 9,780
  • 7
  • 39
  • 56
1

let a = new Object();

Creates a new Object, printed as {}.

let a = {};

Creates a new Object, printed as {}. Not really different from the approach above.

let a = Object;

Object is the constructor, calling it will return a new object but it's better practice to use the new keyword for code conventions. I personally choose to use let a = {}; in JavaScript. A constructor is a function, which is why the console told you it just created a function.

Randy
  • 9,419
  • 5
  • 39
  • 56