Arrays & Basic Array Operations (methods) Flashcards
What is an array in JS?
A data structure for storing values of different types.
const friends = [ 'Micheal', 'Steve', 'Peter' ]; What other way can an array be created in JS apart from the literal syntax above?
const friends = new Array (‘Micheal’, ‘Steve’, ‘Peter’ );
How are elements in an array accessed?
Elements in an array are accessed using their indexes.
Example:
console.log(friends[0]);
How do you get the length of an array?
The length of an array can be gotten by using the Array.length property.
Example:- console.log(friends.length);
How do you access the last element in an array?
console.log(friends[friends.length-1]);
//This is because the .length property is not zero based while arrays are zero based, hence the length of the array - 1 will give the last item in the array.
Explain the JavaScript Array.push() Method.
The Array.push() method adds a new item or new items to the end of an array and returns the new length.
Explain the JavaScript Array.unshift() Method.
The Array.unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
Explain the JavaScript Array.pop() Method.
The Array.pop() method removes the last element from an array and returns that element.
Explain the JavaScript Array.shift() Method.
The Array.shift() method removes the first element from an array and returns that removed element.
Explain the JavaScript Array.indexOf() Method.
The Array.indexOf() method returns the first index at which a given element can be found in the array or -1 if it is not present.
Explain the JavaScript Array.includes() Method.
The Array.includes() method determines whether an array includes a certain value among it entries , returning true or false as appropriate.