Does JavaScript pass by reference?
In JavaScript, primitives (string
, num
, bool
, null
, undefined
) are by value—functions can't alter the original variable. Objects (arrays
, functions
, any other non-primitive types) are passed by reference—specifically, by copy of reference; hence, functions can modify the original object.
Example: A JavaScript version of a "name tag switcher"
Critical distinctions
Objects are indeed passed by a copy of reference or pass-by-sharing in JavaScript. Here's the two cents worth of difference:
- Modifying an object's property inside a function modifies the original object.
- Reassigning the whole object within a function doesn't touch the original reference, proving it's not a pass-by-reference in the strictest sense.
Example:
Brave the edge cases
Edge cases bring the excitement! Following are scenarios that often trigger "Oh, I didn't know that" moments.
- With nested objects, changes to nested properties propagate, which means you can't hide in inception levels.
- Functions that are passed as object properties, or in arrays, come with an outside scope's season pass. Lo and behold, closures!
- Changes to arrays, our object type in disguise, reflect outside the functions too.
Now, be practical!
Having in-depth knowledge of JavaScript's data passage therapy has real-world implications.
- Object properties are like shared notes among all who hold the reference. Use responsibly.
- When dealing with new data, reassigning within functions helps to keep things tidy outside.
- Passing large objects? Congratulations! You've hit a memory-saving variable assignment deal.
Function parameters are double agents!
JavaScript's approach to passing parameters offers the best of both worlds—value and reference. Knowing this inside-out adds finesse to:
- State management: Handling your application's tiny variables like a boss.
- Immutability: You can choose to keep some things constant, like the speed of light.
- Pure functions: Mindfully saving your function from harmful side effects.
Your object, your command!
To deftly maneuver objects in JavaScript:
- Understand object property mutability and the immutability of referential relations.
- Know that the
=
operator can be deceptive in object contexts. Remember, the referee can switch sides at halftime! - Each copy of a reference is like a master key — any changes unlocks it for all holders.
References
Was this article helpful?