Team LiB
Previous Section Next Section

Object Types and Primitive Types

After reading this chapter, it should be clear that, as discussed in Chapter 3, each primitive type has a corresponding built-in object. This is not obvious since primitive data values are transparently converted to the appropriate object when one of its properties is accessed. There are two circumstances when you might prefer to declare a variable as a built-in object rather than use the primitive type. The first is if you plan to add instance properties to the object. Because you cannot add instance properties to primitive data, you must declare the variable as the appropriate object if you wish to do so. The second reason is if you wish to pass a reference to the data to a function. Because JavaScript uses call-by-value, a copy of primitive data is passed to function arguments; the function cannot modify the original. Objects, on the other hand, are reference types. Called functions receive a copy of the reference and can therefore modify the original data.

Outside of these two cases, there is no particular reason to prefer the object versions of Boolean, string, or number data over their primitive counterparts. It is highly unlikely that choosing one over the other will have any significant effect on performance or memory usage. The programmer should use whichever one he or she finds most convenient. Examination of real-world scripts on the Web reveals that the vast majority use primitive types.


Team LiB
Previous Section Next Section