JohnJohnGa
JohnJohnGa

Reputation: 15685

var Object = new Object();

>> typeof Object
"function"   

>> var Object = new Object();

>> typeof Object
"object"

>> var a = new Object()
TypeError: Object is not a constructor

Why it is possible to use "Object" as a valid variable name?

Upvotes: 4

Views: 1456

Answers (5)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385174

That your code is valid is controlled by two factors:

  • Object is not a "reserved word".

  • Names re-declared in a scope "hide" entities of the same name that were declared in an outer scope. That means that your local variable Object may hide the function Object that exists elsewhere.

Upvotes: 1

Andreas Grech
Andreas Grech

Reputation: 107950

These are the reserved words in JavaScript:

break
case
catch
continue
debugger
default
delete
do
else
finally
for
function
if
in
instanceof
new
return
switch
this
throw
try
typeof
var
void
while
with

Upvotes: 2

user113716
user113716

Reputation: 322492

"Why "Object" is not a specific keyword?"

Because it's not defined as such in the specification.

ECMAScript 7.6.1 Reserved Words

Upvotes: 1

Kammy
Kammy

Reputation: 431

What you have done here is using Object class Constructor you have declared Object as new variable. And when you use Object() it will refer to object declared before named Object.

Upvotes: 0

pimvdb
pimvdb

Reputation: 154838

new Object() will return an object as does {}. So yes, typeof new Object() === "object". The constructor is (as any constructor) a function, so typeof Object === "function".

If you replace the constructor with an object, however, then typeof Object === "object" since Object has become an object like {}. It's the same logic as typeof {} === "object".

Object is not a keyword at all.

Upvotes: 3

Related Questions