Arrays
In this lesson, we define arrays and their methods in JavaScript!
We'll cover the following...
So, arrays can hold integers, strings, characters, functions, and pretty much any other data type, including other arrays simultaneously! Look at the following example. anotherArray contains two arrays, a string, and a function! The elements can be accessed or ‘indexed’ with square brackets. The first element in an array is accessed with 0 (as on line 8), the second element is accessed with 1, and so on. The array index starts from 0.
Note: In JavaScript, the JS engine will try to use contiguous memory locations for the array elements to optimize the operations. However, if we do stuff like leave blank spaces or try to add properties, the engine has to bank on the Array being an Object and treat it as such. If we are using the Array as an array should be, we can assume that it is like a C++ array. There may be some challenges or examples where are flexing the muscle of the Array in JS-specific ways. In such a case, it becomes an object and so our assumptions about the running time of code would need to be changed.
Important Array Functions
Let’s have a look at some useful, built-in JavaScript array functions. A word of caution, though, don’t use these to replace your interview answers. For example, if you are asked to sort an array, don’t simply use the sort() function to answer the question!
The push() function
Use this function to add a single element to the end of an array.
The complexity of the push() operation will be ...