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() > Adding and Updating Values in Arrays

Adding and Updating Values in Arrays

A value can be added to an array at any index, at any time. Below, we are adding a value to the numeric index 50 of an empty array. What about all the indexes before 50? Well, like I said, you can add a value to an array at any index, at any time. But, if you add a value to the numeric index 50 of an empty array, JavaScript will fill in all of the necessary indexes before it with undefined values.

Live Code

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

var myArray = [];
myArray[50] = 'blue';
console.log(myArray.length); /* logs 51 (0 is counted) because JS created 
                             values 0 to 50 before "blue"*/

</script></body></html>

Additionally, considering the dynamic nature of JavaScript and the fact that JavaScript is not strongly typed, an array value can be updated at any time and the value contained in the index can be any legal JavaScript value. Below, I change the value at the numeric index 50 to an object.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

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

  

Start a Free Trial


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