Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

9. Array() > Setting Array Length can Add or Remove Values

Setting Array Length can Add or Remove Values

The length property of an array object can be used to get or set the length of an array. As shown above, setting the length higher than the actual number of values contained in the array will add undefined values to the array. What you might not expect is that you can actually remove values from an array by setting the length value to a number less than the number of values contained in the array.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

var myArray = ['blue', 'green', 'orange', 'red'];
console.log(myArray.length); // logs 4
myArray.length = 99;
console.log(myArray.length); /* logs 99, remember we set the length, 
                             not an index */
myArray.length = 1; // removed all but one value, so index [1] is gone!
console.log(myArray[1]); // logs undefined

console.log(myArray); // logs '["blue"]'
</script></body></html>

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint