Reputation: 8765
Is undefined
an object in javascript?
ex: string
is an object because string.length
exists.
Upvotes: 1
Views: 1150
Reputation: 1074168
No, undefined
is a primitive, the only instance of the Undefined type. Details in the specification, but the primitive types are (currently):
(It's likely more will be added, such as BigDecimal.)
Everything else is an object.
ex: string is an object because string.length exists.
Strings are not usually objects, they're primitives that are coerced to their object equivalent when necessary (in theory; in practice, JavaScript engines optimize away that conversion). For instance:
let s = "foo";
s
is a primitive string, typeof s
is "string"
. But when you try to access a property on it (s.length
for instance, or s.toUpperCase()
), the primitive string is coerced to a String object. (Again: in theory — and sometimes in practice, particularly in loose mode.) That's how it gets access to its methods, which are defined on String.prototype
. You can also create a String object intentionally: new String("foo")
but there's almost never any good reason to do that.
This same is true for all of the other primitive types except Undefined and Null, which have no object type equivalent (if you try to access a property on undefined
or null
, you get a TypeError). (This is a bit confusing for Null, because typeof null
is "object"
and null
is used when something object-typed needs a "no value" value. But Null is a primitive type, and null
is a primitive value.)
Upvotes: 5
Reputation: 49
undefined is a property of the global object; i.e., it is a variable in global scope. The initial value of undefined is the primitive value undefined. A variable that has not been assigned a value is of type undefined. Eg. In the following code, the variable x is not initialized, and the if statement evaluates to true.
var x;
if (x === undefined) {
// these statements execute
}
else {
// these statements do not execute
}
Upvotes: -1
Reputation:
4.3.2 primitive value
member of one of the types Undefined, Null, Boolean, Number, Symbol, or String
6.1 ECMAScript Language Types
An ECMAScript language type corresponds to values that are directly manipulated by an ECMAScript programmer using the ECMAScript language. The ECMAScript language types are Undefined, Null, Boolean, String, Symbol, Number, and Object. An ECMAScript language value is a value that is characterized by an ECMAScript language type.
6.1.1 The Undefined Type
The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value has the value undefined.
Upvotes: 0
Reputation: 370689
undefined
is a primitive:
The global undefined property represents the primitive value undefined. It is one of JavaScript's primitive types.
Strings are primitives too. When you use <referenceToString>.<someProperty>
, the interpreter wraps the string in an object wrapper so that it can reference String.prototype
.
Upvotes: 6