1

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" }
1
  • 1
    Objects in JS are reference types. What you are saying is var a = {x:1}, b = a;. When you do like a = null; then the reference chain gets broken and b remains as originally referenced (instantiated) {x:1}. Commented Dec 1, 2021 at 18:30

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.