Javascript arguments are passed by value
Base data types in js are stored in stacks:
Js reference data types, variable names and addresses stored in the stack, variable values stored in the heap memory:
Here’s how to pass parameters to a function:
Pass by value
var value = 1;
function foo(v) {
v = 2;
console.log(v); / / 2
}
foo(value);
console.log(value) / / 1
Copy the code
Before the change:
Stack memory | Heap memory |
---|---|
value: 1 | |
v: 1 |
After the change:
Stack memory | Heap memory |
---|---|
Value: 1. | |
v:2 |
When you pass a value to foo, you copy a value. Let’s say the copy is called _value. The function changes the value of _value without affecting the original value.
Pass by reference
var obj = {
value: 1
};
function foo(o) {
o.value = 2;
console.log(o.value); / / 2
}
foo(obj);
console.log(obj.value) / / 2
Copy the code
Before the change:
Stack memory | Heap memory |
---|---|
Obj, o —–> Pointer address | {value: 1} |
After the change:
Stack memory | Heap memory |
---|---|
Obj, o —–> Pointer address | {value: 2} |
var obj = {
value: 1
};
function foo(o) {
o = 2;
console.log(o); / / 2
}
foo(obj);
console.log(obj.value) / / 1
Copy the code
Before the change:
Stack memory | Heap memory |
---|---|
Obj, o —–> Pointer address | {value: 1} |
After the change:
Stack memory | Heap memory |
---|---|
Obj —–> Pointer address | {value: 2} |
o:2 |
Obj. Value = 1 obj. Value = 1 obj. Value = 1 obj. Value = 2
Passing a copy of the reference to the object, i.e. assuming that the memory address of obj is 0011, then the variable O is also stored at that address on the stack. If we assign the constant 2 to O, o is not stored at 0011, but at 2.