Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete operator behavior on non existing indexed element of an array?

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.

like image 617
P K Avatar asked Jan 05 '12 20:01

P K


1 Answers

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 
like image 198
Andreas Köberle Avatar answered Oct 03 '22 09:10

Andreas Köberle