Deleting an array element

JavaScript FAQ | JavaScript Arrays FAQ  

Question: How do I delete an array element in JavaScript?

Answer: Two different ways to delete an element

myArray[n]
from
myArray
are:
delete myArray[n]
(faster, but leaves a gap at index
n
)
myArray.splice(n,1)
(slower, but does not leave a gap in the array)

For example, to delete the

myArray[5]
element from
myArray
(leaving a gap), use the
delete
statement:
delete myArray[5]
. You can use
myArray.hasOwnProperty(n)
to check if the element
myArray[n]
is present in
myArray
. Note that setting the array element to
null
or to
undefined
is not equivalent to deleting the element, as shown in the example below:
var myArray = new Array(0,10,20,30,40);  


// myArray[5] does not exist yet
document.write(myArray[5]);                // 

document.write(typeof myArray[5]);         // 

document.write(myArray.hasOwnProperty(5)); // 


// create myArray[5] by assignment
myArray[5] = 1;                            // 

document.write(typeof myArray[5]);         // 

document.write(myArray.hasOwnProperty(5)); // 


myArray[5] = null;                         // 

document.write(typeof myArray[5]);         // 

document.write(myArray.hasOwnProperty(5)); // 


myArray[5] = undefined;                    // 

document.write(typeof myArray[5]);         // 

document.write(myArray.hasOwnProperty(5)); // 


delete myArray[5];                            

document.write(myArray[5]);                // 

document.write(typeof myArray[5]);         // 

document.write(myArray.hasOwnProperty(5)); // 

Just like deleting an array element, you can also delete an object property. However, in JavaScript you cannot delete a variable declared with the
var
keyword at the time of first use.

Copyright © 1996-2018, JavascriptFAQ.net.