This blog post explains that JavaScript has two main kinds of values: primitive values and objects. There are several things one needs to be aware of when working with them.
> var obj = {};
> obj.foo = 123; // write
123
> obj.foo // read
123
> {} === {}
false
> var obj = {};
> obj === obj
true
> var var1 = {};
> var var2 = var1;
> var1.foo = 123;
123
> var2.foo
123
> var str = "abc";
> str.foo = 123; // write - ignored
123
> str.foo // read
undefined
> "abc" === "abc"
true
That means that the identity of a primitive is its value, it does not have an individual identity.
Ignore wrapper types as much as possible. In contrast to other programming languages such as Java, you will rarely notice them.The three primitive types string, number and boolean have corresponding types whose instances are objects: String, Number, Boolean. They are sometimes called wrapper types and converting between primitive and wrapper is simple:
> typeof "abc"
'string'
> typeof new String("abc")
'object'
> "abc" instanceof String
false
> new String("abc") instanceof String
true
> "abc" === new String("abc")
false
Wrapper instances are objects and there is no way of comparing objects in JavaScript, not even via non-strict equals == (which is more lenient than the preferred strict equals ===).
> var a = new String("abc");
> var b = new String("abc");
> a == b
false
> a == a
true
> "abc".charAt === String.prototype.charAt
true
There are two ways that this borrowing is done. The old way is to convert a primitive to a
wrapper, on the fly. The new way (via ECMAScript 5 strict mode) is to transparently use the methods from
the wrapper’s prototype. The following code illustrates the difference [inspired by “The Secret Life of JavaScript Primitives”].
// Methods in Object.prototype are available to all primitives
Object.prototype.getType = function() {
return typeof this;
};
Object.prototype.getTypeStrict = function() {
"use strict";
return typeof this;
};
console.log("".getType()); // object
console.log("".getTypeStrict()); // string
> typeof "abc"
'string'
> typeof 123
'number'
> typeof {}
'object'
> typeof []
'object'
typeof returns the following strings:
| Value | Result |
| Undeclared variables | "undefined" |
| undefined | "undefined" |
| null | "object" |
| Booleans | "boolean" |
| Numbers | "number" |
| String | "string" |
| Functions | "function" |
| All other values | "object" |
Comments:
> typeof undeclaredVariable
'undefined'
> undeclaredVariable
ReferenceError: undeclaredVariable is not defined
value instanceof ConstructorThe above expression returns true if value is an instance of Constructor. It is equivalent to:
Constructor.prototype.isPrototypeOf(value)Most objects are instances of Object, because their prototype chain ends with Object.prototype. Primitives are not an instance of anything.
> "abc" instanceof Object
false
> "abc" instanceof String
false