6

Why does delete operator return true if I try to delete non existing indexed element of an array?

More precisely deletion of undefined is true in javascript?

var arr = ['a','b','c','d'];

console.log(delete arr[2000]);  //true why?

console.log(delete aaaaa);     //true  why not reference error?

console.log(delete arrr[2000]);  //reference error  it's okay i think

I don't understand difference between 2nd and 3rd deletion. Both should ideally give reference error.

4
  • 1
    because it worked, arr[2000] is not there anymore. Commented Jan 5, 2012 at 20:26
  • do u mean deletion of undefined is true? arr[2000] was undefined Commented Jan 5, 2012 at 20:27
  • The real question is what are you trying to do, this might be a classical XY Problem case. Commented Jan 5, 2012 at 20:30
  • updated my answer to your edits Commented Jan 5, 2012 at 20:45

1 Answer 1

9

From the MDN:

Returns false only if the property exists and cannot be deleted. It returns true in all other cases.

edit:

here you just delete a in your scope, mostly the window scope

console.log(delete aaaaa);     //true  why not reference error?

so its the same as:

console.log(delete window.aaaaa);     //true  

here arrr is undefined and you get an reference error before the delete method is called

console.log(delete arrr[2000]);  //reference error  it's okay i think 
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.