I am new to JavaScript and try to understand some core concepts.
I created an array and assigned it to the variable fullNames. Then I declared another variable (fullName) and assigned the first (and only) element of fullNames array to that variable.
As I checked, if I modify the first element (which is an object) of fullNames array the value is also modified for element assigned to the fullName variable, which basically means that element wasn't simply copied to fullName variable and that fullName simply points to the first element (object) in fullNames array. Right?
However, if then I remove all elements from an array initially assigned to fullNames variable, the fullName variable to which the first element was assigned still logs this same element.
So, what happens in that case? Why firstName still points to some object if all elements were removed from an array prior I log firstName to console?
let fullNames = [{ name: "Name", surname: "Surname" }];
let fullName = fullNames[0];
fullNames.length = 0;
console.log(fullNames); // displays []
console.log(fullName); // displays { name: "Name", surname: "Surname" }
Setting the length of the array to zero clears out the array but does not edit the content. So all references still exist for values that would have been included in the array.
The rules are different for objects though, which may be the behavior you are expecting.
var string = "abc";
var obj = {
test: 123
};
var arr = [1, 2, 3, 4];
var bigArr = [];
bigArr.push(string, obj, arr);
console.log(bigArr);
bigArr.length = 0;
console.log(bigArr);
console.log(string, obj, arr);
var obj2 = obj;
console.log(obj, obj2);
delete obj2.test;
console.log(obj, obj2);