Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
Referencing of an element of an array after emptying the array

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" }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!