Key Concepts:
undefined
, null
, Symbol) and pass-by-reference for compound types (Objects and Arrays). The typeof
operator determines the assignment method.In short: JavaScript's reference behavior differs significantly from languages with explicit pointers. Only compound data structures are passed by reference.
Terminology:
Note: JavaScript's scalar types are primitives, unlike some languages (like Ruby) with scalar reference types. JavaScript's primitive values are immutable, while compound values are mutable.
This article was originally published on Medium.
Summary of Key Points:
typeof
operator determines whether a value is assigned by value or by reference.Examples:
Pass-by-Value (Primitives):
let batman = 7; let superman = batman; //assign-by-value superman++; console.log(batman); //7 console.log(superman); //8
Pass-by-Reference (Compound Values):
let flash = [8, 8, 8]; let quicksilver = flash; //assign-by-reference quicksilver.push(0); console.log(flash); //[8, 8, 8, 0] console.log(quicksilver); //[8, 8, 8, 0]
Creating New References:
Reassigning a compound value creates a new reference:
let firestorm = [3, 6, 3]; let atom = firestorm; //assign-by-reference atom = [9, 0, 9]; //value is reassigned (creates new reference) console.log(firestorm); //[3, 6, 3] console.log(atom); //[9, 0, 9]
References in Functions:
let batman = 7; let superman = batman; //assign-by-value superman++; console.log(batman); //7 console.log(superman); //8
Modifying Original Compound Value within a Function:
let flash = [8, 8, 8]; let quicksilver = flash; //assign-by-reference quicksilver.push(0); console.log(flash); //[8, 8, 8, 0] console.log(quicksilver); //[8, 8, 8, 0]
Creating a Shallow Copy:
let firestorm = [3, 6, 3]; let atom = firestorm; //assign-by-reference atom = [9, 0, 9]; //value is reassigned (creates new reference) console.log(firestorm); //[3, 6, 3] console.log(atom); //[9, 0, 9]
Assigning Primitives by Reference (using Objects):
let magneto = [8, 4, 8]; (function(x) { //IIFE x.push(99); x = [1, 4, 1]; //reassign variable (creates new reference) x.push(88); })(magneto); console.log(magneto); //[8, 4, 8, 99]
Conclusion:
Understanding JavaScript's reference system is crucial for writing efficient and bug-free code.
(FAQs section omitted for brevity, but could be re-added based on need.)
The above is the detailed content of Quick Tip: How JavaScript References Work. For more information, please follow other related articles on the PHP Chinese website!