- Item 3: Beware of Implicit Coercions
- Item 4: Prefer Primitives to Object Wrappers
- Item 5: Avoid using == with Mixed Types
- Item 6: Learn the Limits of Semicolon Insertion
- Item 7: Think of Strings As Sequences of 16-Bit Code Units
Item 4: Prefer Primitives to Object Wrappers
var s = new
In some ways, a String object behaves similarly to the string value it wraps. You can concatenate it with other values to create strings:
" world"; // "hello world"
You can extract its indexed substrings:
4]; // "o"
But unlike primitive strings, a String object is a true object:
"hello"; // "string" typeof s; // "object"
This is an important difference, because it means that you can’t compare the contents of two distinct String objects using built-in operators:
var s1 = new
"hello"); var s2 = new
"hello"); s1 === s2; // false
Since each String object is a separate object, it is only ever equal to itself. The same is true for the nonstrict equality operator:
s1 == s2; // false
toUpperCase(); // "HELLO"
A strange consequence of this implicit wrapping is that you can set properties on primitive values with essentially no effect:
"hello".someProperty; // undefined
Things to Remember
- Object wrappers for primitive types do not have the same behavior as their primitive values when compared for equality.
- Getting and setting properties on primitives implicitly creates object wrappers.