1

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.

2
  • 3
    removeName does not return anything, so it produces undefined by default. Commented Nov 22, 2021 at 16:43
  • @VLAZ I just forgot to write in (), and when I write I get the same result. Commented Nov 22, 2021 at 16:46

2 Answers 2

1

Looking at the definition of removeName, you're expected to send a person. You're currently not doing that, and you're 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);

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

1 Comment

Basically I have an outbreak. If we do not write at the beginning let user = { name : "name", surname: "surname" }; And let's start with function removeName (person) then how can it be done? for example to accept the person object as a parameter, and to modifies the person object by deleting the property name field.
1

Delete returns true. However you return nothing, so the function retuns undefined.

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

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.