Skip to content

Instantly share code, notes, and snippets.

@phillippelevidad
Last active November 18, 2023 21:11
Show Gist options
  • Save phillippelevidad/64be7263f7f92755d1d101cb950843ae to your computer and use it in GitHub Desktop.
Save phillippelevidad/64be7263f7f92755d1d101cb950843ae to your computer and use it in GitHub Desktop.
References vs values in function parameters in JS
const assert = require("assert");
// When we change the contents of an object, we can see
// the change outside the function.
function f1(obj) {
obj.a += 1;
assert.deepStrictEqual(obj, { a: 2 });
}
const obj1 = { a: 1 };
f1(obj1);
assert.deepStrictEqual(obj1, { a: 2 });
// But when we destructure an object, we can NOT see the change
// outside the function.
function f2({ a }) {
a += 1;
assert.strictEqual(a, 2);
}
const obj2 = { a: 1 };
f2(obj2);
assert.deepStrictEqual(obj2, { a: 1 });
// This is because destructuring is requivalent to
// declaring a new variable and assigning the value of the
// property to it.
function f3(obj) {
let a = obj.a;
a += 1;
assert.strictEqual(a, 2);
}
const obj3 = { a: 1 };
f3(obj3);
assert.deepStrictEqual(obj3, { a: 1 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment