Sobes.tech
Junior

Kuidas sa mõistad, mis on viite kaudu edastamine?

sobes.tech AI

Vastus AI-lt

In JavaScript, primitive data types (strings, numbers, booleans, null, undefined, Symbol, BigInt) are passed by value. This means that when assigning or passing to a function, the actual value is copied.

Objects (including arrays and functions) are passed and copied by reference. Essentially, what is copied is not the object itself, but the reference to the memory location where it is stored.

// Passing by value
let a = 10;
let b = a; // Copies the value 10
b = 20;
console.log(a); // 10, changes to 'b' do not affect 'a'

// Passing by reference
let obj1 = { value: 10 };
let obj2 = obj1; // Copies the reference to the object
obj2.value = 20;
console.log(obj1.value); // 20, changes through 'obj2' affect 'obj1' because they point to the same object

When passing an object to a function, the function receives a copy of the reference. Changes to the object's properties inside the function will affect the original object because the reference is the same. However, if a new object is assigned to the variable inside the function, the original object remains unchanged because the reference will point to a different memory area.

function modifyObject(obj) {
  obj.newValue = 30; // Modifies the original object
}

function assignNewObject(obj) {
  obj = { anotherValue: 40 }; // The 'obj' inside the function now points to a new object
}

let myObject = { initialValue: 10 };
modifyObject(myObject);
console.log(myObject); // { initialValue: 10, newValue: 30 }

let anotherObject = { initialValue: 10 };
assignNewObject(anotherObject);
console.log(anotherObject); // { initialValue: 10 }, the original object remains unchanged