javascriptobjectprimitive-types

What values are objects in JavaScript?


It is said that all values are objects in JavaScript. But I found that the primitive values like null, undefined, true, 'foo' are not objects. Is that true?

What objects are there in JavaScript and what are the non-objects in JavaScript? What is a primitive value actually?

If I'm understanding correctly, the following is true?

var str1 = "hello world!"; // primitive value
var str2 = String("hello world!");// object value

Solution

  • JavaScript has two classes of values

    A major difference between primitives and objects is that primitives are immutable and custom/adhoc properties cannot be assigned to primitive values.


    The number, string, and boolean primitive types have corresponding Object types: Number, String, and Boolean. However, there are no corresponding Object types for undefined or null - these values are lonely singletons.

    The associated types contain the [prototype] which, when applied with implicit conversions, allows primitives to otherwise "act like" objects in that methods can be invoked on them. For instance, "foo".trim() calls the String.prototype.trim function.

    The Number/String/Boolean functions, when not used as constructors, also act as conversions to the applicable primitive values.

    "foo"                       // is string (primitive)
    String("foo")               // is string (primitive)
    new String("foo")           // is String (object)
    "foo" === String("foo")     // -> true
    "foo" === new String("foo") // -> false
    

    One should generally use the primitive types to avoid confusion.