You are on page 1of 50

Lecture # 4

Arrow functions, Arrays and Array Methods

Presented by:
Ahsan Ali Mansoor
4+ Years of experience / Team Lead (React JS)
Sr. Full Stack JavaScript Developer at eBridge.tech
Arrow functions
With ECMAScript 2015, JavaScript got arrow functions, which are mainly
syntactic sugar for defining function expressions. Here's how the arrow
function version of the add function looks like:

function add(a,b){ return a+b; } //normal function before ES5


var add = (a, b) => a + b; //arrow function

Arrow functions mostly behave like function expressions. They are


expressions rather than statements, which allows them to appear in
expression position.

Just like functions expressions, arrow functions aren't hoisted — only function
declarations are.
Arrow functions
There are two main differences between arrow functions and function
expressions, though:

1. Arrow functions cannot be named. The arrow function syntax is very


concise and meant for simple, brief functions. It doesn't allow for a
function name.
2. Arrow functions lexically bind the current this value. The treatment
of this within an arrow function is different than within non-arrow function
expressions.
Arrow functions
The brevity of the arrow function syntax is extremely helpful for small functions
passed to a higher-order function such as map:
const numbers = [1, 2, 3];
const doubled = numbers.map(n => 2 * n);

• Removed function keyword


• Refine callbacks & higher order functions
• For single line code ‘return’ keyword no longer required
• For single argument no parenthesis required
• Auto bind this keyword
Arrow functions
Auto bind this keyword
const test = {
name: 'test object',
createAnonFunction: function() {
return function() {
console.log(this.name); console.log(arguments);
}},
createArrowFunction: function() {
return () => {
console.log(this.name); console.log(arguments);
}}
};

const anon = test.createAnonFunction('hello', 'world'); //call anon(); get empty result


const arrow = test.createArrowFunction('hello', 'world'); //call arrow(); get correct result
Arrays
There exists a special data structure named Array, to store ordered
collections.

It is not convenient to use an object here, because it provides no methods to


manage the order of elements. We can’t insert a new property “between”
the existing ones. Objects are just not meant for such use..
Arrays Declaration
• Two syntaxes for creating an array
• Get an element by its number in square brackets
• Replace an element
• Add a new one to the array
• Total count of the elements in the array is its length
• Array can store elements of any type
• Simplest way to clear the array is: arr.length = 0;
Array Methods push vs shift
Data structure Queue

A queue is one of the most common uses of an array. In computer science, this means an ordered
collection of elements which supports two operations:

push() appends an element to the end and returns the length.


shift() get/return an element from the beginning, advancing the queue, so that the 2nd element
becomes the 1st
Arrays support both operations.
For queues, we have FIFO (First-In-First-Out).
Array Methods Push & Pop
Data structure Stack

There’s another use case for arrays – the data structure named stack.
It supports two operations:

push adds an element to the end.


pop takes an element from the end.
So new elements are added or taken always from the “end”.
For stacks, the latest pushed item is received first, that’s also called LIFO (Last-In-First-Out) principle.
Array Methods
pop: Takes an element from the end.
push: Add an element to the end.
shift: Takes an element from the Start.
unshift: Add an element to the First.

Methods push and unshift can add multiple elements at once:


fruits.push("Orange", "Peach");
fruits.unshift("Pineapple", "Lemon");
Performance
Methods push/pop run fast, while shift / unshift are slow.

The shift operation must do 3 things:


1. Remove the element with the index 0.
2. Move all elements to the left, renumber them from the index 1 to 0, from 2 to 1 and so on.
3. Update the length property.
Array Methods
The JavaScript method toString() converts an array to a string of (comma separated) array values.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.toString();

The join() method also joins all array elements into a string.

It behaves just like toString(), but in addition you can specify the separator:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.join(" * ");
Array Methods - Sorting
The sort() method sorts the elements of an array in place (in place is an
algorithm) and returns the sorted array. The default sort order is ascending,
built upon converting the elements into strings, then comparing their
sequences of UTF-16 code units values.

const months = ['March', 'Jan', 'Feb', 'Dec'];


months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const numbers = [1, 30, 4, 21, 100000]; (for numbers sorting we need a compare function)
numbers.sort();
console.log(numbers);
// expected output: Array [1, 100000, 21, 30, 4]
Sorting with compare function
Syntax: arr.sort([compareFunction])

compareFunction Specifies a function that defines the sort order. If omitted, the array
elements are converted to strings, then sorted according to each character's Unicode code
point value.
firstEl The first element for comparison.
secondEl The second element for comparison.

Note : In UTF-16, Unicode characters above \uFFFF are encoded as two


surrogate code units, of the range \uD800-\uDFFF.
Sorting with compare function
So, the compare function has the following form:
function compare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}
Sorting with compare function
To compare numbers instead of strings, the compare function can simply
subtract b from a. The following function will sort the array in ascending order
(if it doesn't contain Infinity and NaN):

function compareNumbers(a, b) {
return a - b;
}

var numbers = [4, 2, 5, 1, 3]; ES2015 provides arrow function expressions with even
shorter syntax.
numbers.sort(function(a, b) { return a - b; });
console.log(numbers); // [1, 2, 3, 4, 5] let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 2, 3, 4, 5]
Sorting with compare function
Objects can be sorted, given the value of one of their properties.
var items = [ { name: 'Edward', value: 21 }, { name: 'Sharpe', value: 37 }, { name: 'And', value: 45 }, { name: 'The', value: -12
}, { name: 'Magnetic', value: 13 }, { name: 'Zeros', value: 37 } ];

// sort by value
items.sort(function (a, b) { return a.value - b.value; });

// sort by name
items.sort(function(a, b) {
var nameA = a.name.toUpperCase(); // ignore upper and lowercase
var nameB = b.name.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) { return -1; }
if (nameA > nameB) { return 1; }
// names must be equal
return 0;
});
Store Expression Results
var numArray = [2, 3+3, 4+4] //Result will be numArray = [2,6,8]

function myfunc(){ return "anything"}


var myArr = [2, 3+3, myfunc()] //Result myArr = [2, 6, "anything"]
Array Methods - Splice
The arr.splice(start) method is a Swiss army knife for arrays. It can do everything: insert,
remove and replace elements.

Syntax: arr.splice(indextoStart, numberofelements to delete, elements to be added)


Let’s start with the deletion:

let arr = ["I", "study", "JavaScript"];

arr.splice(1, 1); // from index 1 remove 1 element & return the removed element

console.log( arr ); // ["I", "JavaScript"]

Easy, right? Starting from the index 1 it removed 1 element.


Array Methods - Splice
In the next example we remove 3 elements and replace them with the other two:

let arr = ["I", "study", "JavaScript", "right", "now"];


// remove 3 first elements and replace them with another
arr.splice(0, 3, "Let's", "dance");

alert( arr ) // now ["Let's", "dance", "right", "now"]

Here we can see that splice returns the array of removed elements:

let arr = ["I", "study", "JavaScript", "right", "now"];


// remove 2 first elements
let removed = arr.splice(0, 2);

alert( removed ); // "I", "study" <-- array of removed elements


Array Methods - Splice
The splice method is also able to insert the elements without any removals.

For that we need to set deleteCount to 0:

let arr = ["I", "study", "JavaScript"];

// from index 2
// delete 0
// then insert "complex" and "language"
arr.splice(2, 0, "complex", "language");

alert( arr ); // "I", "study", "complex", "language", "JavaScript"


Array Methods - Splice
Negative indexes allowed

Here and in other array methods, negative indexes are allowed. They specify the position
from the end of the array, like here:

let arr = [1, 2, 5];

// from index -1 (one step from the end)


// delete 0 elements,
// then insert 3 and 4
arr.splice(-1, 0, 3, 4);

alert( arr ); // 1,2,3,4,5


Array Methods - Slice
The method arr.slice is much simpler than similar-looking arr.splice.

The syntax is:

arr.slice([start], [end])

It returns a new array copying to it all items from index start to end (not including end).
Both start and end can be negative, in that case position from array end is assumed.

It’s similar to a string method str.slice, but instead of substrings it makes subarrays.
Array Methods - concat
The method arr.concat creates a new array that includes values from other arrays and
additional items.

The syntax is:


arr.concat(arr1, arr2)
It accepts any number of arguments – either arrays or values.

The result is a new array containing items from arr, then arg1, arg2 etc.

If an argument argN is an array, then all its elements are copied. Otherwise, the argument
itself is copied.
arr.concat(arr1, 2,3,4)
Array Methods - concat
For instance:

let arr = [1, 2];

// create an array from: arr and [3,4]


alert( arr.concat([3, 4]) ); // 1,2,3,4

// create an array from: arr and [3,4] and [5,6]


alert( arr.concat([3, 4], [5, 6]) ); // 1,2,3,4,5,6

// create an array from: arr and [3,4], then add values 5 and 6
alert( arr.concat([3, 4], 5, 6) ); // 1,2,3,4,5,6
Array Methods
indexOf / lastIndexOf & includes
The methods arr.indexOf, arr.lastIndexOf and arr.includes have the same syntax and do
essentially the same as their string counterparts, but operate on items instead of
characters:

arr.indexOf(item, from) – looks for item starting from index from, and returns the index
where it was found, otherwise -1.
arr.lastIndexOf(item, from) – same, but looks for from right to left.
arr.includes(item, from) – looks for item starting from index from, returns true if found
otherwise false.
array.Includes
It checks that if element exist in the array returns Boolean true otherwise
returns false.

let numArray = [1,2,3,4]


console.log(numArray.includes(5)) // return false
Array Methods
For instance:

let arr = [1, 0, false];

alert( arr.indexOf(0) ); // 1
alert( arr.indexOf(false) ); // 2
alert( arr.indexOf(null) ); // -1

alert( arr.includes(1) ); // true


Array Methods
Note that the methods use === comparison. So, if we look for false, it finds exactly false and
not the zero.

If we want to check for inclusion, and don’t want to know the exact index, then arr.includes
is preferred.

Also, a very minor difference of includes is that it correctly handles NaN, unlike
indexOf/lastIndexOf:

const arr = [NaN];


alert( arr.indexOf(NaN) ); // -1 (should be 0, but === equality doesn't work for NaN)
alert( arr.includes(NaN) );// true (correct)
Array Methods
Array.isArray
Arrays do not form a separate language type. They are based on objects.

So typeof does not help to distinguish a plain object from an array:

alert(typeof {}); // object


alert(typeof []); // same

…But arrays are used so often that there’s a special method for that: Array.isArray(value). It
returns true if the value is an array, and false otherwise.

alert(Array.isArray({})); // false
alert(Array.isArray([])); // true
For of loop (introduced in es6)
let fruits = ["Apple", "Orange", "Plum"];

// iterates over array elements


for (let fruit of fruits) {
console.log( fruit );
}

The for..of loop doesn’t give access to the number(index) of the current element but just its value
and in most cases that’s enough. And it’s shorter.
Higher Order Array Functions
Higher order functions are functions that operate on other functions, either by taking them
as arguments or by returning them.
In simple words, A Higher-Order function is a function that receives a function as an
argument or returns the function as output.

For example, Array.prototype.map, Array.prototype.filter and Array.prototype.reduce are


some of the Higher-Order functions built into the language.
• forEach
• map
• find
• filter
• Sort
• Reduce
Array Methods
Syntax:
orignalArray.higherOrderFunction(callback function)
orignalArray.higherOrderFunction((item, index, orignalArray) => {})

The callback function accepts three arguments:

• Value of current element in iteration


• Index of the current element
• Array itself on which we are looping through
Higher Order Array Functions
1- Array.prototype.forEach
forEach() replaces the old for and while loop syntax with a modern and simple
syntax.
forEach() takes a callback function and run that callback function on each
element of array one by one in ascending order.
forEach() works as a traditional for loop looping over the array and providing
you array elements to do operations on them.
Higher Order Array Functions
• Use forEach If you just need to iterate through the array and print it.
• forEach() returns an undefined. It just calls the callback function on each
element in the array, but does not return anything.

let fruits = ['apple', 'banana', 'strawberry', 'orange'];


fruits.forEach(fruit => console.log(fruit));

Output:
// apple banana strawberry orange
// undefined (because forEach returns undefined)
Higher Order Array Functions
Another example where we mutating the original array

let temp = [1, 4, 9];


temp.forEach((item, index) => {
return temp[index] = item * 3;
});

// temp is now [3, 12, 27]


Higher Order Array Functions
2- Array.prototype.map
The map() method creates a new array with the results of calling a provided
function on every element in the calling array.
map() calls a provided callback function once for each element in an array, in
order, and constructs a new array from the results.

The callback accepts three arguments:


• Value of current element in iteration
• Index of the current element
• Array itself on which we are looping through
Higher Order Array Functions
Example:
let numbers = [1, 4, 9];
let triples = numbers.map((item) => {
return item * 3;
});

// numbers is still [1, 4, 9]


// triples is [3, 12, 27]
Higher Order Array Functions
forEach() vs map()
• forEach() doesn’t return anything from the callback(instead returns
undefined), while map() returns a new array from the callback function.

• Between forEach() and map() with respect to speed. map() is faster.

• The original array that the map() function iterates through is immutable.
This means it cannot be changed, and the map() has to return a new array
with the updated items.
Array Methods
Imagine we have an array of objects. How do we find an object with the specific condition?

Here the arr.find(fn) method comes in handy.

The syntax is:

let result = arr.find((item, index, array) => {


// if true is returned, item is returned and iteration is stopped
// for falsy scenario returns undefined
});
Array Methods
For example, we have an array of users, each with the fields id and name. Let’s find the one
with id == 1:

let users = [
{id: 1, name: "John"},
{id: 2, name: "Pete"},
{id: 3, name: "Mary"}
];

let user = users.find(item => item.id == 1);

alert(user.name); // John
Array Methods
In real life arrays of objects is a common thing, so the find method is very useful.

Note that in the example we provide to find the function item => item.id == 1 with one
argument. That’s typical, other arguments of this function are rarely used.

The arr.findIndex method is essentially the same, but it returns the index where the
element was found instead of the element itself and -1 is returned when nothing is found.
Higher Order Array Functions
3- Array.prototype.filter
• Whenever you have to filter an array JavaScript inbuilt method to filter your
array is the right choice to use.
• Filter let you provide a callback for every element and returns a filtered
array.
• The main difference between forEach and filter is that forEach just loop
over the array and executes the callback but filter executes the callback
and check its return value.
• If the value is true element remains in the resulting array but if the return
value is false the element will be removed for the resulting array.
• Also take notice filter does not update the existing array it will return a
new filtered array every time.
Array Methods
filter
The find method looks for a single (first) element that makes the function return true.

If there may be many, we can use arr.filter(fn).

The syntax is similar to find, but filter returns an array of all matching elements:

let results = arr.filter(function(item, index, array) {


// if true item is pushed to results and the iteration continues
// returns empty array if nothing found
});
Array Methods
For instance:

let users = [
{id: 1, name: "John"},
{id: 2, name: "Pete"},
{id: 3, name: "Mary"}
];

// returns array of the first two users


let someUsers = users.filter(item => item.id < 3);

console.log(someUsers.length); // 2
Higher Order Array Functions
Example:
var sample = [1, 2, 3]
var result = sample.filter(elem => elem !== 2)
/* output */
[1, 3]
Higher Order Array Functions
4- Array.prototype.reduce
As the name already suggest reduce method of the array object is used
to reduce the array to one single value.

var sample = [1, 2, 3]


var sum = sample.reduce((sum, elem) => sum + elem)
console.log(sum)
Higher Order Array Functions
reduce takes a callback ( like every function we talked about ). Inside this
callback we get two arguments sum & elem. The sum is the last returned
value of the reduce function.
So that is how reduce works it reduces the array into one single value and
returns it upon completion.
Higher Order Array Functions

Returns Usage

forEach Undefined Iterate over the array

Map New array Iterate over array and return a new array based on
original array. It does not mutate the original Array.

Filter New filtered array Execute the callback on each item or provided array
and returns the new filtered array on the basis of
true value.

reduce One single value Reduce the array into a single value.
Coding Challenge III – Tip Calculator
Use of: function, array, if else / switch
John and his family went on a holiday and went to 3 different restaurants. The
bills were $124, $48 and $268.
To tip the waiter a fair amount, john created a simple tip calculator (as a
function). He likes to tip 20% of the bill when is less than $50, 15% when the
bill is between $50 and $200, and 10% if the bill is more than $200.

In the end John would like to have 2 arrays:


1. Containing all three tips (one for each bill)
2. Containing all three final paid amounts (bill + tip)

Note: to calculate percentage = Bill Amount * percentage / 100

You might also like