Working with ECMA5 and ES6
Promises
Oswald Campesato
Consultant/Training:
www.iquarkt.com
ocampesato@yahoo.com
What You’ll Learn in this Workshop
A fast-paced introduction to many things (*):
Nested functions/Closures/Currying
Map/filter/reduce
ES6 arrow notation
synchronous & asynchronous functions
Promises
Tail Recursion
(*) ECMA5/ES6 features useful for ReactJS/Angular 2
Can you explain (*)…
• 1) the difference between call and apply [**]
• 2) the purpose of map (it’s covered)
• 3) the purpose of apply/bind/call [**]
• 4) how closures work (it’s covered)
• 5) how to debug JS performance problems [**]
(*) All these topics are interview questions
#2 and #4 are briefly discussed in this workshop
[**] read online tutorials
Simple Function in JS
Option #1:
var a = 10, b = 5;
var c1 = a + b; // 15
Option #2:
var add = function (num1, num2) {
return num1+num2;
}
var c2 = add(10,5); // 15
Nested Functions in JS (Currying)
Option #3:
var add2 = function (num1) {
return function(num2) {
return num1+num2;
}
}
var c3 = add2(10)(5); //15
var addTen = add2(10); // a function
var c4 = addTen(5); //15
Advantages of Currying
+ “Pure” functions (no side effects)/Fewer bugs
+ Alternative to ‘bind’ method
https://derickbailey.com/2016/06/24/currying-a-
functional-alternative-to-fn-bind
https://blog.simpleblend.net/functional-javascript-
concepts-currying
Working with JS Closures
function addFactor(n1) {
var factor = 3;
return function inner(n2) {
console.log(”n1 = "+n1+" n2 = "+n2);
return (n1+n2)*factor;
}
}
var answer = addFactor(7)(5);
• See MultipleArgs2.html
• Learn about IIFE (online articles)
More Nested Functions
• function func4(arg1) {
• console.log("* Inside func4 arg1: "+arg1);
• return function inner1(arg2) {
• console.log("* Inside func4/inner1 arg2: "+arg2);
• return function inner2(arg3) {
• console.log("* Inside func4/inner2 arg3: "+arg3);
• return function inner3(arg4) {
• console.log("* Inside func4/inner3 arg4: "+arg4);
• }
• }
• }
• } // MultipleArgs1.html
Exercises for Nested Functions
• 1) Write a function that matches this signature:
func1(a1)(a2,a3);
• 2) Write a function that matches this signature:
func2(a1)(a2,a3,a4)(a5,a6);
• Read “four rules of ‘this’” (Kyle Simpson):
a) https://github.com/getify/You-Dont-Know-
JS/blob/master/this%20&%20object%20prototypes/ch2.
md
b) http://rainsoft.io/6-ways-to-declare-javascript-
Useful ECMA5 Methods
• indexOf()
• forEach()
• filter()
• map()
• reduce()
The indexOf() Method
• The indexOf() method returns the first index at
which a given element can be found in an array
• Returns -1 if the element does not exist
// EverySomeFunctions.html
The forEach() Method
• The forEach() method: iterates through an iterable
collection
• // ES6 Map collection: ES6Collections.html
• var myMap = new Map();
• myMap.set(1, "one");
• myMap.set("two", 2);
• myMap.set(true, false);
• myMap.set("foo", "bar");
myMap.forEach(function (value, key, mapObj) {
console.log("value: ",value,"key: ",key);
});
The filter() Method (1a)
• The filter() method // Filter1.html
• <script>
• let arr1 = ['apple','','banana','','fig','grape'];
• let arr2 = arr1.filter(item => item.endsWith("e"));
• let arr3 = arr1.filter(Boolean);
• console.log("arr1 = "+arr1);
• console.log("arr2 = "+arr2);
• console.log("arr3 = "+arr3);
• </script>
The filter() Method (1b)
• Output from Filter1.html:
• arr1 = apple,,banana,,fig,grape
• arr2 = apple,grape
• arr3 = apple,banana,fig,grape
The filter() Method (2a)
• The filter() method // Filter2.html
• <script>
• let arr1 = [1,2,3,4,5,6,7,8,9,10];
• let arr2 = arr1.filter(item => item > 5);
• let arr3 = arr1.filter(item => item % 2 == 0);
• let arr4 = arr1.filter(item => item < 5)
• .filter(item => item % 2 == 0);
• console.log("arr1 = "+arr1);
• console.log("arr2 = "+arr2);
• console.log("arr3 = "+arr3);
• console.log("arr4 = "+arr4);
• </script>
The filter() Method (1b)
• Output from Filter2.html:
• arr1 = 1,2,3,4,5,6,7,8,9,10
• arr2 = 6,7,8,9,10
• arr3 = 2,4,6,8,10
• arr4 = 2,4
The filter() Method (3)
• The filter() method // MapFilter.html
• var items = [1,2,3,4,5,6,7,8,9,10,11,
• 12,13,14,15,16,17,18,19,20];
• var even = [];
• even = items.filter(function(item) {
• return item % 2 == 0;
• });
• console.log("even = "+even);
The map() Method (1a)
• The map() method // MapFilter.html
• var items = [1,2,3,4,5,6,7,8,9,10,11,
• 12,13,14,15,16,17,18,19,20];
• var double = [];
• double = items.map(function(num) {
• return num * 2;
• });
console.log("double = "+double);
• 2) var double2 = items.map(num => 2*num);
console.log("double2 = "+double2);
The map() Method (1b)
• Output from MapFilter1.html:
• even = 2,4,6,8,10,12,14,16,18,20
• double =
2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,
36,38,40
The reduce() Method (1)
The reduce() method:
• reduces an array to a single value executes a provided
function for each
• value of the array (from left-to-right)
• return value of the function is stored in an
"accumulator" (result/total).
NB: reduce() execute the function for array elements
with values
The reduce() Method (2)
• var nums = [1, 2, 3, 4, 5];
• function getSum(total, num) {
• return total + num;
• }
• function myFunction(arr) {
• console.log("sum = "+arr.reduce(getSum));
• }
• myFunction(nums);
What about ES6?
• classes (still functions ‘under the hood’)
• template strings
• arrow functions
• constants & block scoped variables
• spread and rest
• destructuring
• modules
• NodeJS: v6 supports 93% of ES6
• no module system (import/export system)
ES6 Constructs: let and for
• 'var' is still scoped to functions
• use 'let' for block scope
•
• var arr = ['a', 'b', 'c'];
• for(let i=0; i<arr.length; i++) {
• console.log(`item = ${arr[i]}`);
• };
• try {
• console.log(i); // Reference error
• } catch (err) {
• console.log(`${err}`);
• }
• // LetFor.html
ES6 Construct: const
• use 'const' for read-only properties
• Example #1:
• 'use strict';
• var i;
• for(i=0; i<10; i+=1) {
• j = i; let k = i;
• }
• console.log(j); // 9
• console.log(k); // undefined
• Example #2: this use of 'const‘ is valid:
• const items = {};
• items.name = "dave";
• console.log(items); <--- valid code
ES6 ‘rest’ feature
• function show(a,b,…others) {
• console.log(a);
• console.log(b);
• console.log(others[0]);
• console.log(others[1]);
• }
• show(1,2,3,4,5);
• // output = ?
ES6 ‘spread’ feature
• const add = (a,b) => a+b;
• let nums = [4,7];
• // both invocations produce the same result:
• add(nums[0], nums[1]);
• add(...nums);
• let newarr = ['a','b', ...nums,'c','d'];
• // result: ['a','b', 4, 7, 'c', 'd'];
ES6 ‘destructuring’ feature
• Example 1:
• let items = ['a', 'b', 'c'];
• let [x1,x2,x3] = items;
• Example 2:
• let myModule = {
• func1: function(width),
• func2: function(height),
• func3: function(name)
• }
• let {f1, f2} = myModule;
• f1(15);
• f2(40);
ECMA5 vs TypeScript Functions
• ECMA5 version:
• function add(a,b) {
• return a+b;
• }
• add(1,4); // 5
• add(1,’4'); // 14 (valid in JavaScript)
• TypeScript version:
• function add(a:number, b:number) {
• return a+b;
• }
• add(1,2); // 3
• add(1,'2'); // <--- (error in TypeScript)
ES6 Constructs: arrow notation (1)
• let items = [1,2,3,4,5,6,7,8];
• let double = items.map((x) => {return 2*x})
• console.log("double = "+double);
• let even = items.filter((x) => {return x % 2 == 0})
• console.log("even = "+even);
• // ArrowFunctions1.html
ES6 Constructs: arrow notation (2)
let upper1 = items.map((x) => {return 'a'+x})
.map((x) => {return x.toUpperCase()})
console.log("upper1 = "+upper1);
// output = ?
let upper2 = items.filter((x) => {return x % 2 == 0})
.map((x) => {return 'z'+x})
.map((x) => {return x.toUpperCase()})
console.log("upper2 = "+upper2);
// output = ?
• // ArrowFunctions1.html
Simple Examples of ES6 Classes
• class MyClass { // does nothing useful
• constructor() { }
• showItems() {}
• }
• class MyClass2 {
• this.msg = "hello world” // <- ‘this’ not needed here in TypeScript
• constructor() { }
• showMsg() {
• console.log(this.msg); // <- ‘this’ required for ES6 and TypeScript
• }
• }
• var myc = new MyClass2();
• myc.showMsg(); // hello world
Working with Immutable.js
https://dzone.com/articles/introduction-to-immutablejs-and-functional-program
• var oddSquares = Immutable.Seq.of(1,2,3,4,5,6,7,8)
• .filter(x => x % 2).map(x => x * x);
• // performs minimum to get the result
• console.log("result0 = "+oddSquares.get(0)); // 9
• console.log("result1 = "+oddSquares.get(1)); // 9
• var list1 = Immutable.List.of(1,2,3);
• var list2 = list1.withMutations(function (list) {
• list.push(4).push(5).push(6);
• });
• console.log("list1 = "+list1);
• console.log("list2 = "+list2);
// Immutable1.html
Other ES6 Collections
• Set and WeakSet collections (add and forEach)
• Map and WeakMap collections (set and forEach)
• ES6Collections.html
• https://github.com/bevacqua/es6
Lodash Methods now in ES6
• map, filter, reduce
• head and tail
• rest and spread
• curry, partial, pick
https://www.sitepoint.com/lodash-features-replace-es6
Simple Iteration: Factorial
• factorial(n) {
• var prod = 1;
• for(var i=1; i<=n; n++) {
• prod *= i;
• console.log(“factorial “+i+” = “+prod);
• }
• return prod;
• }
• console.log(“factorial 5 = “+factorial(5));
• console.log(“factorial 10 = “+factorial(10));
Exercises: Iteration
• 1) EvenP: calculate the product of the even integers
between 1 and n
• 2) Prime: check if the positive integer n is prime (its
only divisors are 1 and itself)
• 3) print the primes between 2 and 100
• 4) Goldbach’s conjecture: every even number greater
than 4 can be written as a sum of two odd primes:
write a function to show it’s true up to 100 (use #3)
• 5) use #4 to find even numbers with multiple
solutions, such as 14 (=3+11 = 7+7)
Simple Recursion: Factorial
• factorial(n) {
• if(n <= 1) return 1;
• else return n * factorial(n-1)
• }
• console.log(“factorial 5 = “+factorial(5));
• console.log(“factorial 10 = “+factorial(10));
Tail Recursion: Factorial
• factorial(n, prod) {
• if(n <= 1) return prod;
• else return factorial(n-1, n*prod)
• }
• console.log(“factorial 5 = “+factorial(5,1));
• console.log(“factorial 10 = “+factorial(10,1));
Exercises: Recursion
1) use Euclid’s algorithm to find the GCD of two positive
integers (GCD = Greatest Common Divisor)
Example: GCD(10,24) = 2
2) use #1 to find the LCM of two positive integers
(where LCM = Lowest Common Multiple)
Example: LCM(10,24) = 120
3) Use recursion to calculate Fibonacci(20)
4) Calculate 10 values of Ackermann’s function
Synchronous Method Invocation
• Given the following sequence:
• func1();
• func2();
• func3();
• func4();
• Here is the in-order Function Execution:
• 1) func1 executes
• 2) func2 executes
• 3) func3 executes
• 4) func4 executes
Asynchronous Method Invocation
• Given the following sequence:
• func1();
• setTimeout(func2, 0); <= asynchronous
• setTimeout(func3, 0); <= asynchronous
• func4();
• Here is the out-of-order Function Execution:
• 1) func1 executes
• 2) func4 executes
• 3) func2 executes
• 4) func3 executes
Exercises: Sync and Async
• 1) add console.log() messages to the four functions
and invoke them synchronously
• 1) add console.log() messages to the four functions
and invoke them asynchronously
What are ES6 Promises?
• A read-only view to a single future value
• determine success/error in the .then() method
• If you have a promise, it’s ready to resolve (non-lazy)
• Immutable: resolve or reject only once
• Intended for avoiding “callback hell”
• Uncancellable (for now)
Creating a Promise
• let p = new Promise(resolve, reject) => {
• myAsyncMethod((err,value) => {
• if(err) {
• reject(err);
• else {
• resolve(value);
• }
• });
• });
Error Handling with Promises: catch
• p.catch(error => {
• if(error instanceof MyErrorType) {
• return Promise.resolve(“passed”);
• } else {
• throw error;
• });
• });
Exercises: Promises
• Download zip file with code samples:
• Promises1.html
• Promises2.html
• Promises3.html
• ....
• Promises11.html
Miscellaneous Topics
• 1) ES6 and arrow functions:
http://rainsoft.io/when-not-to-use-arrow-functions-in-
javascript
• 2) “Promises” article by Kyle Simpson:
https://blog.getify.com/promises-wrong-ways
• 3) ES6 “cheatsheet”:
https://www.toptal.com/javascript/javascript-es6-cheat-
sheet
Recent/Upcoming Books and Training
1) HTML5 Canvas and CSS3 Graphics (2013)
2) jQuery, CSS3, and HTML5 for Mobile (2013)
3) HTML5 Pocket Primer (2013)
4) jQuery Pocket Primer (2013)
5) HTML5 Mobile Pocket Primer (2014)
6) D3 Pocket Primer (2015)
7) Python Pocket Primer (2015)
8) SVG Pocket Primer (2016)
9) CSS3 Pocket Primer (2016)
10) Angular 2 Pocket Primer (2016)

ECMA5 and ES6 Promises

  • 1.
    Working with ECMA5and ES6 Promises Oswald Campesato Consultant/Training: www.iquarkt.com ocampesato@yahoo.com
  • 2.
    What You’ll Learnin this Workshop A fast-paced introduction to many things (*): Nested functions/Closures/Currying Map/filter/reduce ES6 arrow notation synchronous & asynchronous functions Promises Tail Recursion (*) ECMA5/ES6 features useful for ReactJS/Angular 2
  • 3.
    Can you explain(*)… • 1) the difference between call and apply [**] • 2) the purpose of map (it’s covered) • 3) the purpose of apply/bind/call [**] • 4) how closures work (it’s covered) • 5) how to debug JS performance problems [**] (*) All these topics are interview questions #2 and #4 are briefly discussed in this workshop [**] read online tutorials
  • 4.
    Simple Function inJS Option #1: var a = 10, b = 5; var c1 = a + b; // 15 Option #2: var add = function (num1, num2) { return num1+num2; } var c2 = add(10,5); // 15
  • 5.
    Nested Functions inJS (Currying) Option #3: var add2 = function (num1) { return function(num2) { return num1+num2; } } var c3 = add2(10)(5); //15 var addTen = add2(10); // a function var c4 = addTen(5); //15
  • 6.
    Advantages of Currying +“Pure” functions (no side effects)/Fewer bugs + Alternative to ‘bind’ method https://derickbailey.com/2016/06/24/currying-a- functional-alternative-to-fn-bind https://blog.simpleblend.net/functional-javascript- concepts-currying
  • 7.
    Working with JSClosures function addFactor(n1) { var factor = 3; return function inner(n2) { console.log(”n1 = "+n1+" n2 = "+n2); return (n1+n2)*factor; } } var answer = addFactor(7)(5); • See MultipleArgs2.html • Learn about IIFE (online articles)
  • 8.
    More Nested Functions •function func4(arg1) { • console.log("* Inside func4 arg1: "+arg1); • return function inner1(arg2) { • console.log("* Inside func4/inner1 arg2: "+arg2); • return function inner2(arg3) { • console.log("* Inside func4/inner2 arg3: "+arg3); • return function inner3(arg4) { • console.log("* Inside func4/inner3 arg4: "+arg4); • } • } • } • } // MultipleArgs1.html
  • 9.
    Exercises for NestedFunctions • 1) Write a function that matches this signature: func1(a1)(a2,a3); • 2) Write a function that matches this signature: func2(a1)(a2,a3,a4)(a5,a6); • Read “four rules of ‘this’” (Kyle Simpson): a) https://github.com/getify/You-Dont-Know- JS/blob/master/this%20&%20object%20prototypes/ch2. md b) http://rainsoft.io/6-ways-to-declare-javascript-
  • 10.
    Useful ECMA5 Methods •indexOf() • forEach() • filter() • map() • reduce()
  • 11.
    The indexOf() Method •The indexOf() method returns the first index at which a given element can be found in an array • Returns -1 if the element does not exist // EverySomeFunctions.html
  • 12.
    The forEach() Method •The forEach() method: iterates through an iterable collection • // ES6 Map collection: ES6Collections.html • var myMap = new Map(); • myMap.set(1, "one"); • myMap.set("two", 2); • myMap.set(true, false); • myMap.set("foo", "bar"); myMap.forEach(function (value, key, mapObj) { console.log("value: ",value,"key: ",key); });
  • 13.
    The filter() Method(1a) • The filter() method // Filter1.html • <script> • let arr1 = ['apple','','banana','','fig','grape']; • let arr2 = arr1.filter(item => item.endsWith("e")); • let arr3 = arr1.filter(Boolean); • console.log("arr1 = "+arr1); • console.log("arr2 = "+arr2); • console.log("arr3 = "+arr3); • </script>
  • 14.
    The filter() Method(1b) • Output from Filter1.html: • arr1 = apple,,banana,,fig,grape • arr2 = apple,grape • arr3 = apple,banana,fig,grape
  • 15.
    The filter() Method(2a) • The filter() method // Filter2.html • <script> • let arr1 = [1,2,3,4,5,6,7,8,9,10]; • let arr2 = arr1.filter(item => item > 5); • let arr3 = arr1.filter(item => item % 2 == 0); • let arr4 = arr1.filter(item => item < 5) • .filter(item => item % 2 == 0); • console.log("arr1 = "+arr1); • console.log("arr2 = "+arr2); • console.log("arr3 = "+arr3); • console.log("arr4 = "+arr4); • </script>
  • 16.
    The filter() Method(1b) • Output from Filter2.html: • arr1 = 1,2,3,4,5,6,7,8,9,10 • arr2 = 6,7,8,9,10 • arr3 = 2,4,6,8,10 • arr4 = 2,4
  • 17.
    The filter() Method(3) • The filter() method // MapFilter.html • var items = [1,2,3,4,5,6,7,8,9,10,11, • 12,13,14,15,16,17,18,19,20]; • var even = []; • even = items.filter(function(item) { • return item % 2 == 0; • }); • console.log("even = "+even);
  • 18.
    The map() Method(1a) • The map() method // MapFilter.html • var items = [1,2,3,4,5,6,7,8,9,10,11, • 12,13,14,15,16,17,18,19,20]; • var double = []; • double = items.map(function(num) { • return num * 2; • }); console.log("double = "+double); • 2) var double2 = items.map(num => 2*num); console.log("double2 = "+double2);
  • 19.
    The map() Method(1b) • Output from MapFilter1.html: • even = 2,4,6,8,10,12,14,16,18,20 • double = 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34, 36,38,40
  • 20.
    The reduce() Method(1) The reduce() method: • reduces an array to a single value executes a provided function for each • value of the array (from left-to-right) • return value of the function is stored in an "accumulator" (result/total). NB: reduce() execute the function for array elements with values
  • 21.
    The reduce() Method(2) • var nums = [1, 2, 3, 4, 5]; • function getSum(total, num) { • return total + num; • } • function myFunction(arr) { • console.log("sum = "+arr.reduce(getSum)); • } • myFunction(nums);
  • 22.
    What about ES6? •classes (still functions ‘under the hood’) • template strings • arrow functions • constants & block scoped variables • spread and rest • destructuring • modules • NodeJS: v6 supports 93% of ES6 • no module system (import/export system)
  • 23.
    ES6 Constructs: letand for • 'var' is still scoped to functions • use 'let' for block scope • • var arr = ['a', 'b', 'c']; • for(let i=0; i<arr.length; i++) { • console.log(`item = ${arr[i]}`); • }; • try { • console.log(i); // Reference error • } catch (err) { • console.log(`${err}`); • } • // LetFor.html
  • 24.
    ES6 Construct: const •use 'const' for read-only properties • Example #1: • 'use strict'; • var i; • for(i=0; i<10; i+=1) { • j = i; let k = i; • } • console.log(j); // 9 • console.log(k); // undefined • Example #2: this use of 'const‘ is valid: • const items = {}; • items.name = "dave"; • console.log(items); <--- valid code
  • 25.
    ES6 ‘rest’ feature •function show(a,b,…others) { • console.log(a); • console.log(b); • console.log(others[0]); • console.log(others[1]); • } • show(1,2,3,4,5); • // output = ?
  • 26.
    ES6 ‘spread’ feature •const add = (a,b) => a+b; • let nums = [4,7]; • // both invocations produce the same result: • add(nums[0], nums[1]); • add(...nums); • let newarr = ['a','b', ...nums,'c','d']; • // result: ['a','b', 4, 7, 'c', 'd'];
  • 27.
    ES6 ‘destructuring’ feature •Example 1: • let items = ['a', 'b', 'c']; • let [x1,x2,x3] = items; • Example 2: • let myModule = { • func1: function(width), • func2: function(height), • func3: function(name) • } • let {f1, f2} = myModule; • f1(15); • f2(40);
  • 28.
    ECMA5 vs TypeScriptFunctions • ECMA5 version: • function add(a,b) { • return a+b; • } • add(1,4); // 5 • add(1,’4'); // 14 (valid in JavaScript) • TypeScript version: • function add(a:number, b:number) { • return a+b; • } • add(1,2); // 3 • add(1,'2'); // <--- (error in TypeScript)
  • 29.
    ES6 Constructs: arrownotation (1) • let items = [1,2,3,4,5,6,7,8]; • let double = items.map((x) => {return 2*x}) • console.log("double = "+double); • let even = items.filter((x) => {return x % 2 == 0}) • console.log("even = "+even); • // ArrowFunctions1.html
  • 30.
    ES6 Constructs: arrownotation (2) let upper1 = items.map((x) => {return 'a'+x}) .map((x) => {return x.toUpperCase()}) console.log("upper1 = "+upper1); // output = ? let upper2 = items.filter((x) => {return x % 2 == 0}) .map((x) => {return 'z'+x}) .map((x) => {return x.toUpperCase()}) console.log("upper2 = "+upper2); // output = ? • // ArrowFunctions1.html
  • 31.
    Simple Examples ofES6 Classes • class MyClass { // does nothing useful • constructor() { } • showItems() {} • } • class MyClass2 { • this.msg = "hello world” // <- ‘this’ not needed here in TypeScript • constructor() { } • showMsg() { • console.log(this.msg); // <- ‘this’ required for ES6 and TypeScript • } • } • var myc = new MyClass2(); • myc.showMsg(); // hello world
  • 32.
    Working with Immutable.js https://dzone.com/articles/introduction-to-immutablejs-and-functional-program •var oddSquares = Immutable.Seq.of(1,2,3,4,5,6,7,8) • .filter(x => x % 2).map(x => x * x); • // performs minimum to get the result • console.log("result0 = "+oddSquares.get(0)); // 9 • console.log("result1 = "+oddSquares.get(1)); // 9 • var list1 = Immutable.List.of(1,2,3); • var list2 = list1.withMutations(function (list) { • list.push(4).push(5).push(6); • }); • console.log("list1 = "+list1); • console.log("list2 = "+list2); // Immutable1.html
  • 33.
    Other ES6 Collections •Set and WeakSet collections (add and forEach) • Map and WeakMap collections (set and forEach) • ES6Collections.html • https://github.com/bevacqua/es6
  • 34.
    Lodash Methods nowin ES6 • map, filter, reduce • head and tail • rest and spread • curry, partial, pick https://www.sitepoint.com/lodash-features-replace-es6
  • 35.
    Simple Iteration: Factorial •factorial(n) { • var prod = 1; • for(var i=1; i<=n; n++) { • prod *= i; • console.log(“factorial “+i+” = “+prod); • } • return prod; • } • console.log(“factorial 5 = “+factorial(5)); • console.log(“factorial 10 = “+factorial(10));
  • 36.
    Exercises: Iteration • 1)EvenP: calculate the product of the even integers between 1 and n • 2) Prime: check if the positive integer n is prime (its only divisors are 1 and itself) • 3) print the primes between 2 and 100 • 4) Goldbach’s conjecture: every even number greater than 4 can be written as a sum of two odd primes: write a function to show it’s true up to 100 (use #3) • 5) use #4 to find even numbers with multiple solutions, such as 14 (=3+11 = 7+7)
  • 37.
    Simple Recursion: Factorial •factorial(n) { • if(n <= 1) return 1; • else return n * factorial(n-1) • } • console.log(“factorial 5 = “+factorial(5)); • console.log(“factorial 10 = “+factorial(10));
  • 38.
    Tail Recursion: Factorial •factorial(n, prod) { • if(n <= 1) return prod; • else return factorial(n-1, n*prod) • } • console.log(“factorial 5 = “+factorial(5,1)); • console.log(“factorial 10 = “+factorial(10,1));
  • 39.
    Exercises: Recursion 1) useEuclid’s algorithm to find the GCD of two positive integers (GCD = Greatest Common Divisor) Example: GCD(10,24) = 2 2) use #1 to find the LCM of two positive integers (where LCM = Lowest Common Multiple) Example: LCM(10,24) = 120 3) Use recursion to calculate Fibonacci(20) 4) Calculate 10 values of Ackermann’s function
  • 40.
    Synchronous Method Invocation •Given the following sequence: • func1(); • func2(); • func3(); • func4(); • Here is the in-order Function Execution: • 1) func1 executes • 2) func2 executes • 3) func3 executes • 4) func4 executes
  • 41.
    Asynchronous Method Invocation •Given the following sequence: • func1(); • setTimeout(func2, 0); <= asynchronous • setTimeout(func3, 0); <= asynchronous • func4(); • Here is the out-of-order Function Execution: • 1) func1 executes • 2) func4 executes • 3) func2 executes • 4) func3 executes
  • 42.
    Exercises: Sync andAsync • 1) add console.log() messages to the four functions and invoke them synchronously • 1) add console.log() messages to the four functions and invoke them asynchronously
  • 43.
    What are ES6Promises? • A read-only view to a single future value • determine success/error in the .then() method • If you have a promise, it’s ready to resolve (non-lazy) • Immutable: resolve or reject only once • Intended for avoiding “callback hell” • Uncancellable (for now)
  • 44.
    Creating a Promise •let p = new Promise(resolve, reject) => { • myAsyncMethod((err,value) => { • if(err) { • reject(err); • else { • resolve(value); • } • }); • });
  • 45.
    Error Handling withPromises: catch • p.catch(error => { • if(error instanceof MyErrorType) { • return Promise.resolve(“passed”); • } else { • throw error; • }); • });
  • 46.
    Exercises: Promises • Downloadzip file with code samples: • Promises1.html • Promises2.html • Promises3.html • .... • Promises11.html
  • 47.
    Miscellaneous Topics • 1)ES6 and arrow functions: http://rainsoft.io/when-not-to-use-arrow-functions-in- javascript • 2) “Promises” article by Kyle Simpson: https://blog.getify.com/promises-wrong-ways • 3) ES6 “cheatsheet”: https://www.toptal.com/javascript/javascript-es6-cheat- sheet
  • 48.
    Recent/Upcoming Books andTraining 1) HTML5 Canvas and CSS3 Graphics (2013) 2) jQuery, CSS3, and HTML5 for Mobile (2013) 3) HTML5 Pocket Primer (2013) 4) jQuery Pocket Primer (2013) 5) HTML5 Mobile Pocket Primer (2014) 6) D3 Pocket Primer (2015) 7) Python Pocket Primer (2015) 8) SVG Pocket Primer (2016) 9) CSS3 Pocket Primer (2016) 10) Angular 2 Pocket Primer (2016)