Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Deleting Objects in JavaScript. I'm a bit confused with JavaScript's delete operator

I’m a bit confused with JavaScript’s delete operator.I am begginer in JS. Take the following piece of code:

function removeName (person){

   let user = {
       name : "name",
       surname: "surname"
   } ;
   console.log(delete user.name);

}
let x;
x = removeName();
console.log(x);

After this piece of code has been executed,I take as output true and undefinied, I take undefinied because I find it difficult to do object in function but true why? Please I am a beginner, so I think my code is miserable.

This confuses me, because I expected that writing delete user.name would delete it and not just throw a true one.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Looking at the definition of removeName, your expected to send a person. Your currently not doing that, and your placing the person inside the function too, and that would just end up scoping the person to this object.

So based on that info, this is how I assume you meant to write the code.

let user = {
  name : "name",
  surname: "surname"
};

function removeName (person){
   delete person.name;
}

removeName(user);
console.log(user);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading