Objects aren't primitive types

There's a very important contrast between an Object and a variable holding an Object. A JavaScript Object is just like a bag of properties in no particular order, and that's a good way of viewing it. However, a JavaScript variable can't contain an arbitrary number of properties, it can hold only one piece of data. So the variable just contains a bit of data that tracks where the bag is (you can't get at this data), and when there's more than one Object around, which Object bag it is. The actual bag itself is separate from the variable's value.

This is important because up until now, dealing with primitive data has been easy; if a variable contains 2, and another variable gets assigned the value 2, that's fine because 2's are cheap—you can have as many as you like. This is also true for Objects—you can have as many as you like—but it's often the case that one object will be shared between many variables, because it can be too much bother (or even impossible) to copy it. This means

delete
is a bit tricky—it really means "make this variable stop tracking its object". If no variables are tracking an object, then the JavaScript interpreter will throw the object away.

This distinction is particularly important when using functions. Variables can be passed to functions as arguments. Variables can contain primitive types or objects. If you use a primitive type as a function argument, then the argument appearing inside the function is a copy of the one you passed it. This means your original copy can't be damaged from inside the function. However, if you pass an object to a function, a copy isn't made, so you are operating on the exact same object inside the function as outside, with consequences to the object that apply even after the function finishes. To summarize, extra care is required passing objects to functions as they are not proof against accidental damage inside the function.

© 1997 by Wrox Press. All rights reserved.