JavaScript - Lesson 04
JavaScript - Lesson 04
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:
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:
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:
There’s another use case for arrays – the data structure named stack.
It supports two operations:
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 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.
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]
arr.splice(1, 1); // from index 1 remove 1 element & return the removed element
Here we can see that splice returns the array of removed elements:
// from index 2
// delete 0
// then insert "complex" and "language"
arr.splice(2, 0, "complex", "language");
Here and in other array methods, negative indexes are allowed. They specify the position
from the end of the array, like here:
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 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:
// 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.
alert( arr.indexOf(0) ); // 1
alert( arr.indexOf(false) ); // 2
alert( arr.indexOf(null) ); // -1
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:
…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"];
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.
Output:
// apple banana strawberry orange
// undefined (because forEach returns undefined)
Higher Order Array Functions
Another example where we mutating the original array
• 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?
let users = [
{id: 1, name: "John"},
{id: 2, name: "Pete"},
{id: 3, name: "Mary"}
];
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.
The syntax is similar to find, but filter returns an array of all matching elements:
let users = [
{id: 1, name: "John"},
{id: 2, name: "Pete"},
{id: 3, name: "Mary"}
];
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.
Returns Usage
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.