Arrays
In this lesson, we define arrays and their methods in JavaScript!
var ExampleList = [3.14159, 'apple', 23]var EmptyList = []console.log(ExampleList)console.log(EmptyList)
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.
var anArray = [2, 'Educative', 'A']function foo(){console.log('Hello from foo()!');}var anotherArray = [anArray, 'JavaScript', foo, ['yet another array']]console.log(anotherArray[0]) // Elements of 'anArray'console.log(anotherArray[0][1]) // Second element of 'anArray'console.log(anotherArray[1])// 'JavaScript'console.log(anotherArray[3]) // 'yet another anArray'// You can also invoke the functions inside an Array!anotherArray[2]() //'Hello from foo()!'
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.
var array = [1, 3, 5, 'seven']console.log(array)array.push(9)console.log(array)
The complexity of the push()
operation will be ...