DEV Community

Discussion on: A "Gotcha" of JavaScript's Pass-by-Reference

 
bytebodger profile image
Adam Nathaniel Davis • Edited

Excellent examples. And yeah, I've had the same kinda "aha!" moment when I realized that, in simple terms, an object is basically a mutable value. And a scalar (like: a number), is an immutable value.

This also helps to further illustrate the difference between a value, and the variable that holds that value. In most illustrations, the two concepts are interchangeable. But of course, they're not the same thing.

It took me years to really "grok" that anything (in JS, or any other language) could truly be immutable. Because I'd think of simple examples like this:

let count = 0;
count++;
console.log(count);
Enter fullscreen mode Exit fullscreen mode

My previous response would have been, "Obviously, numbers are mutable, otherwise, the 3rd line would return an error or 0." And honestly, that logic mostly "works" when trying to look at your code and determine what can be changed (mutated), and what cannot.

IMHO, this example "feels" much more like immutability:

const count = 0;
count++;
console.log(count);
Enter fullscreen mode Exit fullscreen mode

This obviously doesn't run. But of course, the error isn't spawned because the value is immutable. It's spawned because the variable itself cannot be reassigned.

Some comments have been hidden by the post's author - find out more