Essentials of Array
What is Array?
Arrays are list-like objects. In JavaScript array, neither its length nor the type of its elements is fixed. So its nature totally depends on the user. There are few methods of the array which is considered to be essential for programmers.
filter()
Use case: It creates a new array with all the elements that pass the test implemented by the provided function.
Try it:
Point to be noted
The callback can be invoked with three arguments:
1. the value of the element
2. the index of the element
3. the Array object being traversed
map()
Use case: Returns a new array containing the results of calling a function on every element in the array.
Try it :
Point to be noted
1. You shouldn’t be using map() if you’re not using the array it returns.
2. You shouldn’t use map() you aren’t returning a value from the callback.
forEach()
Use Case: Used to execute a provided method for each element in the array.
Try it:
Point to be noted: There is no way to stop or break a forEach() loop
sort()
Use Case: Sorts the elements of an array.
Try it:
Point to be noted:
1. The value of each code unit is taken separately into account for the comparison.
2. The sort() method can be conveniently used with functional expressions.
shift()
Use Case: Remove an item from the beginning of an Array
Try it :
Point to be noted
1. It will return undefined if the array is empty.
2. The shift() method removes the element at the zeroeth index.
unshift()
Use Case: The unshift method inserts the given values to the beginning of an array.
Try it:
Point to be noted
1. If multiple elements are passed as parameters, they’re inserted in chunks at the beginning of the object, in the exact same order they were passed as parameters.
push()
Use Case: It is used to add one or more elements to the end of an array.
Try it:
Point to be noted
1. It depends on the length of the array where it will start inserting given elements.
2. The push() method is generic.
pop()
Use Case: It is used to remove the last element of the array.
Try it :
Point to be noted
1. It can be applied to objects resembling arrays.
2. It generic in nature.
slice()
Use Case: The slice method returns a selected portion from start to end(where start and end represent the index of items in that array) of an array into a new array.
Try it :
Point to be noted
1. For strings, numbers, and booleans slice() copies the values into the new array.
2. Not string, number, and boolean.
splice()
Use Case: It is used to remove and replace a new element to the arrary.
Try it:
Point to be noted
1. If only one element is removed, an array of one element is returned.
2. If no elements are removed, an empty array is returned.