Introduction
[wp_ad_camp_5]
JavaScript has both primitive and reference types. It has three primitive types: string, numeric, and boolean. Internally, these are small and fixed-sized collection of bytes that are easily and predictably manipulated at the low (primitive) levels of the JavaScript interpreter. Example of strings are ‘This is a string’ and “This is another string”. Numeric values – 1, and 3.1416. Boolean values – true or false. On the other hand, reference types are different. They include objects (including JS built-in objects), Arrays, and functions. Essentially, they can have any number of properties or elements with various types (both primitives and references), so they cannot be manipulated as easily as fixed-size primitive values can.
When working with references, everything is “by reference”. Here I will use the term “reference variable” to mean a variable of reference type, e.g., Object. When you copy reference variables, pass them as arguments to a function, and compare against each other, it is always “by reference”.
Copy by Reference
1 2 3 4 5 6 7 8 9 10 11 | var personObject = {'id': 1, 'name': 'Anthony Hopkins'}; var tempReferenceVariable = personObject; console.log(personObject.name); // This will change the name of the object referred to by personObject as tempReferenceVariable also points to the same object tempReferenceVariable.name = 'Bruce Willis'; console.log(tempReferenceVariable.name); // Even when referring to the personObject reference variable, name still yields 'Bruce Willis' console.log(personObject.name); |
Outputs:
1 2 3 | Anthony Hopkins Bruce Willis Bruce Willis |
Pass by Reference
[wp_ad_camp_4]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var personObject = {'id': 1, 'name': 'Anthony Hopkins'}; var fnChangeName = function(pObject) { // This changes the name from 'Anthony Hopkins' to 'Bruce Willis' // and the effect will be visible outside when the function completes. pObject.name = 'Bruce Willis'; }; console.log(personObject.name) // Call the function and pass the reference variable personObject // to change the name fnChangeName(personObject); console.log(personObject.name); |
Outputs:
1 2 | Anthony Hopkins Bruce Willis |
Compare by Reference
1 2 3 4 5 6 7 8 9 10 11 | var personObjectA = {'id': 1, 'name': 'Anthony Hopkins'}; var personObjectB = {'id': 2, 'name': 'Bruce Willis'}; console.log(personObjectA == personObjectB); console.log(personObjectA === personObjectB); var tempPersonObjectA = personObjectA; var tempPersonObjectB = personObjectB; console.log(personObjectA == tempPersonObjectA); console.log(personObjectB === tempPersonObjectB); |
Outputs:
[wp_ad_camp_3]
1 2 3 4 | false false true true |