note-javascript
===
#### Brief summary of JavaScript language
###### Written by **[Jaehyun Park](https://portfolio-jaey.now.sh/)**
## Table of Contents
* [What is JavaScript?](#What-is-JavaScript?)
* [Obejct Oriented Programming in JavaScript](#Obejct-Oriented-Programming-in-JavaScript)
* [Object in JavaScript](#Object-in-JavaScript)
1. [Prototype Chain](#1.-Prototype-Chain)
2. [Instantiation](#2.-Instantiation)
3. [Inheritance](#3.-Inheritance)
4. [Object-related methods](#4.-Object-related-methods)
* [Execution Context](#Execution-Context)
1. [Scope Chain (Lexical Scope)](#1.-Scope-Chain)
2. [Hoisting](#2.-Hoisting)
3. [Closure](#3.-Closure)
4. ['this' binding](#4.-this-binding)
* [ES6 Features](#ES6-Features)
* [let, const](#let,-const)
* [Classes](#Classes)
* [constuctor](#constuctor)
* [super](#super)
* [new](#new)
* [static method](#static-method)
* [arrow function](#arrow-function)
* [spread operator](#spread-operator)
* [destructuring assignment](#destructuring-assignment)
* [for...of](#for\.\.\.of)
* [Iterator](#Iterator)
* [Generator](#Generator)
* [Iterable](#Iterable)
* [Set, WeakSet](#Set,-WeakSet)
* [Map, WeakMap](#Map,-WeakMap)
* [Template literals](#Template-literals)
* [import...from, export](#import\.\.\.from,-export)
* [Object.is](#Object\.is)
* [ES7 Features](#)
* [Promise](#Promise)
* [ES8 Features](#)
* [Async, Await](#Async,-Await)
* [Advanced Topics](#Advanced-Topics)
* [Enhanced object literals](#Enhanced-object-literals)
* [IIFE (Immediately Invoked Function Expression)](#IIFE-(Immediately-Invoked-Function-Expression))
* [Functional Programming in Javascript](#Functional-Programming-in-Javascript)
1. [Pure and Impure function](#1.-Pure-and-Impure-function)
2. [Higher Order Function (HOF)](#2.-Higher-Order-Function-(HOF))
3. [Currying](#3.-Currying)
4. [Function Composition](#4.-Function-Composition)
What is JavaScript?
---
#### I define JavaScript as a Prototype-based Object Oriented Interpreted Web Programming Language
#### - Prototype-based Object Oriented Language:
* JavaScript gives us the way to reuse exist code by providing inheritence through prototype chaining.
* Encapsulation can be implemented by using its scope chain characteristic (Closure)
#### - Interpreted Language:
* When the particular source code is excuted, it interprete the code and run it and we get results as its output whereas other compile language generates native binary code following ELF format (in case of Linux system) before we run it
> #### V8 engine
> With V8 engine, JavaScript gets quite different from traditional interpreted languages since V8 engine preserves compiled code snippets in its Heap.
> <img src="https://drive.google.com/uc?export=view&id=1vvlIKQqdb6NR6TvXR6zqfZhXxyF6xIMX" alt="s-expression transform" width="400"/>
#### - Web Programming Language:
* JavaScript is the only programming lanugage that web browser can understand and run it
#### - Think More
* Prototype-based language vs Class-based language
* Interpreted language vs Compiled language
Obejct Oriented Programming in JavaScript
---
#### Main purpose of OOP: increasing reusability
#### - **Abstraction** (generalization: IS-A)
> It refers to the ability to filter out unnecessary or unimportant information.
#### - **Inheritance** (specialization: HAS-A, Overriding abstract or virtual attributes)
> Where classes and objects can be derived from parent classes and objects, inheriting all the characteristics and methods and then extending them
* JavaScript doesn't support **Abstract** or **Virtual** keyword
> but you can mimic it as below alternatively
```javascript
// implementation of Abstract class in JavaScript
class Abstract {
constructor() {
if (new.target === Abstract) {
throw new TypeError("Cannot construct Abstract instances directly");
}
if (this.custom_method === undefined) {
// or maybe test typeof this.method === "function"
throw new TypeError("Must override custom_method()");
}
}
}
class Derived1 extends Abstract {
constructor() {
super();
// more Derived-specific stuff here, maybe
}
}
class Derived2 extends Abstract {
constructor() {
super();
// more Derived-specific stuff here, maybe
}
custom_method() {}
}
const a = new Abstract(); // new.target is Abstract, so it throws
const b = new Derived1(); // new.target is Derived but this.custom_method() is undefined, so it throws
const c = new Derived2(); // new.target is Derived and this.custom_method() is defined, so no error
```
#### - **Encapsulation**
> Data Hiding and Access Modifier - public, internal, protected, protected intrnal, private.
> It hides implementation details, the only way to interact with an object is through its public API.
* Javascript does **not** support Access Modifier
> Intead, Encapsulation with private members can be implemented by **Closure** and its lexical scope in Javascript
#### - **Polymorpism**
> Different objects respond to the same request in their own unique way.
* **Overriding** (dynamic polymorpism)
* JavaScript can change its parameter and return type since it doesn't support function Overloading
* **Overloading** (static polymorpism): Overloaded functions have the same name but different arguments
* JavaScript does **NOT** support Overloading
* You should make a wrapper function in order to implement Overloading in JavaScript
```javascript
// implementation of Overloading in Javascript
class Foo {
constructor() { }
bar1(x) { console.log(`bar1: ${x}`) }
bar2(x, y) { console.log(`bar2: ${x} ${y}`) }
bar() {
switch(arguments.length) {
case 1:
this.bar1(arguments[0])
break
case 2:
this.bar2(arguments[0], arguments[1])
break
}
}
}
let foo = new Foo
foo.bar(1)
foo.bar(1, 2)
```
Object in JavaScript
---
* Almost everything exept for **primitive types** (=immutable value - call by value) such as **String, Number, Boolean, null, and undefined, (Symbol)** is deemed an object
* Object is **mutable**, which means its values can be changed instead of referring a new instance, unlike primitive types
* Object is a collection of properties
* Property is an association between a name (key) and a value
### 1. Prototype Chain
JavaScript only has one construct: objects. <u>Each object has a private property which holds a link to another object called its **prototype**</u>. That prototype object has a prototype of its own, and so on <u>until an object is reached with null as its prototype</u>. By definition, null has no prototype, and acts as the final link in this **prototype chain**.
**Two types of prototype property**
* **prototype** is a property of a Function object (eg. Function(), Object(), Array()). It is the prototype of objects constructed by that Function.
* **\_\_proto__** (**[[Prototype]]** in Node) is the internal prototype linkage of a prototype object, pointing to its prototype.
### 2. Instantiation
#### 2-1. Instantiating Object
* **new** : it calls constructor and return a new instance.
```javascript
// Object
let myObj = {a:1}; // using Object Literal
// or
let myObj = new Object(); // using new
myObj.a = 1;
// myObj.__proto__ -> Object() prototype object
```
<img src="https://drive.google.com/uc?export=view&id=1A3jV04VB_1kBbfPXRBdnMX9q9Ob1yO-M" alt="s-expression transform" width="600"/>
#### 2-2. Instantiating Object with Object Literal
* **Object.create()** : creates a new object, using an existing object as the prototype of the newly created object
```javascript
// creates car object using object literal
// car.__proto__ -> Object() prototype object
let car = {
make: 'ford',
model: 'mustang',
year: 1993,
color: 'red',
wheels: 4,
engine: {
cylinders: 4,
size: 2.2
},
showMake: function() {console.log(this.make);},
showColor() {console.log(this.color);}
};
// myCar.__proto__ -> car object -> Object() prototype object
let myCar = Object.create(car);
```
<img src="https://drive.google.com/uc?export=view&id=1teNXN2S7tHOwZfOwSSzKZf5gzXqWAake" alt="s-expression transform" width="600"/>
#### 2-3. Instantiating Object with new
##### 2-3-1. Creating a Person object by using Constuctor
```javascript
// Person.__proto__ -> Function() prototype object -> Object() prototype object
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
this.info = function () {
console.log(`Name:${this.name} Age:${this.age} (${this.sex})`);
}
}
Person.prototype.infoDerived = function() {
console.log(`Name:${this.name} Age:${this.age} (${this.sex})`);
}
// ben.__proto__ -> Person() prototype object -> Object() prototype object
let ben = new Person('Ben Powers', 20, 'M');
ben.info(); // ben.info()
ben.infoDerived(); // ben.__proto__.infoDerived()
```
#### 2-3-2. Creating a Person object using Class
```javascript
// Person.proto__ -> Function() prototype object -> Object() prototype object
class Person {
constructor(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
this.info = function() {
console.log(`Name:${this.name} Age:${this.age} (${this.sex})`);
}
}
infoDerived() {
console.log(`Name:${this.name} Age:${this.age} (${this.sex})`);
}
}
// ben.__proto__ -> Person() prototype object -> Object() prototype object
let ben = new Person('Ben Powers', 20, 'M');
ben.info(); // ben.info()
ben.infoDerived(); // ben.__proto__.infoDerived()
```
<img src="https://drive.google.com/uc?export=view&id=10Nj82wupEGJq2wEgIyQwZ4P7wnY6isFw" alt="s-expression transform" width="600"/>
#### 2-4. Instantiating Array Object
```javascript
// Instantiating Array object
let myArray = ['Yo', 'whadup', '?'];
// myArray.__proto__ -> Array() prototype object -> Object() prototype object
```
<img src="https://drive.google.com/uc?export=view&id=1O4YRGWAlrDQ0biUHMvaotlOuqdO5ylX1" alt="s-expression transform" width="600"/>
#### 2-5. Instantiating Function Object
```javascript
// Function object
function myFunc() {return 3;}
// or
let myFunc = function() {return 3;};
// myFunc.__proto__ --> Function() prototype object --> Object() prototype object
```
<img src="https://drive.google.com/uc?export=view&id=1E17bEcbMpmZcbMBwspwNBUuepgUjxsr2" alt="s-expression transform" width="600"/>
### 3. Inheritance
#### 3-1. Inheritance in ES5
```javascript
// Inheritance in ES5
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
// add method to Person prototype
Person.prototype.eat = function() {console.log(`Yum yum..`);}
Person.prototype.sleep = function() {console.log(`Zzz..`);}
function Student(name, age, sex, number) {
// execute parent constructor first
// pass 'this' and call Person constructor with arguments (name, age, sex).
Person.call(this, name, age, sex);
// add new properties
this.number = number;
}
// inheritance chaining through the prototype
Student.prototype = Object.create(Person.prototype);
// add constructor reference on Student prototype
Student.prototype.constructor = Student;
// add method to Student prototype
Student.prototype.goToSchool = function() {console.log(`Go go..`);}
Student.prototype.leaveSchool = function() {console.log(`Bye!`);}
let ben = new Student('Ben Powers', 20, 'M', 123456);
ben.goToSchool(); // ben.__proto__.goToSchool()
ben.sleep(); // ben.__proto__.__proto__.sleep()
```
#### 3.2 Inheritance in ES6
```javascript
// Inheritance in ES6
class Person {
constructor(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
eat() {console.log(`Yum yum..`);}
sleep() {console.log(`Zzz..`);}
}
class Student extends Person {
constructor(name, age, sex, number) {
// execute parent constructor first
super(name, age, sex);
this.number = number;
}
goToSchool() {console.log(`Go go..`);}
leaveSchool() {console.log(`Bye!`);}
}
let ben = new Student('Ben Powers', 20, 'M', 123456);
ben.goToSchool(); // ben.__proto__.goToSchool()
ben.sleep(); // ben.__proto__.__proto__.sleep()
```
<img src="https://drive.google.com/uc?export=view&id=1p6z8wVsLy-z4BniosB8efHCMzQCbGrCQ" alt="s-expression transform" width="600"/>
### 4. Object-related methods
#### 4-1. Object.create() vs new (ES6)
Object.create() and new, both create new object and inherit prototype object.
However, Object.create() doesn't execute constructor(), so object, which is created by Object.create(), **doesn't bind 'this' from the function object and just refers to the function’s prototype object**.
```javascript
function Dog() {
this.sleep = function(){console.log(`Zzz zzz..`)}
}
Dog.prototype.eat = function() {
console.log(`Yum yum..`);
}
let maddie = new Dog();
maddie.eat(); // Yum yum..
maddie.sleep(); // Zzz zzz..
let buddy = Object.create(Dog.prototype);
buddy.eat(); // Yum yum..
buddy.sleep(); // error!
```
#### 4-2. Object.assign()
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.
The Object.assign() method **only copies enumerable (array, set, map..)** and **own properties** from a source object to a target object.
```javascript
// Merging object
let obj = { a: 1 };
let copy = Object.assign({ b: 2}, obj);
console.log(copy); // { b: 2, a: 1 }
```
#### 4-3. Spread Operator (ES6)
The fundamental idea of the object spread operator (...) is **to create a new plain object using the own properties of an existing object**.
```javascript
// You can also mix in other properties with the object spread operator.
// Order matters:
// The object spread operator will overwrite properties that are defined before it, but not after.
const obj = { a: 'a', b: 'b', c: 'c' };
const obj2 = { a: 1, ...obj, b: null, c: void 0 };
console.log(obj2); // { a: 'a', b: null, c: undefined }
```
#### 4-4. Object.assign() vs Spread Operator
**{ ...obj }** is equivalent to **Object.assign({}, obj)**
However, The **Object.assign()** function modifies its first parameter in place.
<u>If you prefer using **immutable** techniques, the object spread operator is a clear winner</u>.
With **Object.assign()**, you would have to ensure you always pass an empty object {} as the first argument.
#### 4-5. Destructuring Assignment
Using this, we can unpack particular properties from objects.
The destructuring assignment syntax is a JavaScript expression that makes it possible **to unpack values from arrays, or properties from objects, into distinct variables**.
* Array destructuring
```javascript
[a1, a2, ...rest_a] = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(a1); // 1
console.log(a2); // 2
console.log(rest_a); // [3, 4, 5, 6, 7, 8, 9]
```
* Object destructuring
```javascript
let { a1, a2, ...rest_a } = { a1 : 10, a2 : 20, a3 : 30, a4 : 40 };
console.log(a1); // 10
console.log(a2); // 20
console.log(rest_a); // { a3: 30, a4: 40 }
({ a, b } = { a : 10, b : 20}); // need parenthesis () without var, let, const
console.log(a); // 10
console.log(b); // 20
{ c, d } = { c : 30, d : 40}; // error
```
* for of
```javascript
const users = [
{name: 'kim', age: 10, addr:'kor'},
{name: 'joe', age: 20, addr:'usa'},
{name: 'miko', age: 30, addr:'jp'}
];
for(let {name : n, age : a} of users){
console.log(`${n} ${a}`); // kim 10, joe 20, miko 30
}
```
* Assigning to new variable names
```javascript
let {foo: a, bar: b} = {foo: 1, bar: 2};
console.log(`${a} ${b}`) // 1 2
```
* Object destructuring without declaration.
> {a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.
> However, **({a, b} = {a: 1, b: 2})** is valid, as is **const {a, b} = {a: 1, b: 2}**
```javascript
({foo: a, bar: b} = {foo: 1, bar: 2});
console.log(`${a} ${b}`) // 1 2
```
* Nested object destructuring
```javascript
const kim = {
name: 'kim',
age: 10,
addr: 'kor',
friends: [
{name: 'joe', age: 20, addr:'usa'},
{name: 'miko', age: 30, addr:'jp'}
]
};
let { name: userName, friends: [ ,{ name: jpFriend }] } = kim;
console.log(userName); // kim
console.log(jpFriend); // miko
```
* Object destructuring as function parameter
```javascript
let user = {
id: 42,
displayName: 'jdoe',
fullName: {
firstName: 'John',
lastName: 'Doe'
}
};
function userId({id}) {
return id;
}
function whois({displayName, fullName: {firstName: name}}) {
return `${displayName} is ${name}`;
}
console.log(userId(user)); // 42
console.log(whois(user)); // "jdoe is John"
```
Execution Context
---
When function is executed, new execution context gets stacked on top of execution context stack.
* The global execution context is created before any code is executed
* Whenever a function is executed (or called/invoked, these are all synonyms), a new execution context gets created
* Whenever an execution context is created, the engine scans through related source code for variable and function declarations, and put them into memory (Environment (ES5) AO: Activated Object (ES3)). <u>**Hoisting** is perfomed at this stage</u>.
* Every execution context provides **[[Scopes]]**, which refers to its outer scopes, all the way up to the global scope.
* Every execution context provides **‘this’**, which <u>points to the object which is used to call the method</u>
**Execution Context Hierarchy**
<img src="https://drive.google.com/uc?export=view&id=1V7D4AuC77xt_exJGwG76FFrv7fjFsiMa" alt="s-expression transform" width="600"/>
**Execution Context Stack**
<img src="https://drive.google.com/uc?export=view&id=1u6ayoe8X__kdul-6GWC03RBEdpk2a6pr" alt="s-expression transform" width="800"/>
### 1. Scope Chain
The name resolution depends on the location in the source code, which(The name resolution) is defined by where the named variable or function is defined.
<img src="https://drive.google.com/uc?export=view&id=1mb37SrB0onEbL5XwsMpYHg76V_KQcdeD" alt="s-expression transform" width="600"/>
#### 1-1. Variable Declaration
* foo: **global scope**
* **var** foo: **function level scope**
* **let** foo: **block level scope (ES6)** within enclosing statements
* **const** foo: **block level scope (ES6)** within enclosing statements, and read only
* **const Object**(or Function): we can change its properties but we **can NOT re-assign the Object**
```javascript
const sayTo = (name) => `Hello ${name}`;
function sayByeTo(name) {return `Bye ${name}`}
console.log(sayTo('Bill'));
sayTo = sayByeTo // it throws
console.log(sayTo('Bill'));
const obj = {name: 'Ben', };
obj.name = 'Bill'; // it's okay
console.log(obj.name)
obj = {name: 'Yilong', };
console.log(obj.name) // it thorws
```
### 2. Hoisting
the JavaScript engine recognises the declaration of variable and function, and hoists it.
So, variables and functions are available before its declaration.
* **The latest expression is prior to others.**
```javascript
{
sayHello() // Hey!
function sayHello () {
function hello () {
console.log('Hello!')
}
hello()
function hello () {
console.log('Hey!')
}
}
}
```
* **declaration is hoisted but initialisation is NOT hoisted**
```javascript
{
sayHello() // Hello!
function sayHello () {
// Function Declaration
function hello () {
console.log('Hello!')
}
hello()
// Function Expression
let hello = function () {
console.log('Hey!')
}
}
}
```
### 3. Closure
<u>**Closure is a function and lexical environment surrounding the function**</u>.
After outer function is expired, we can keep accessing its local scope variables through the inner function context returned and its scope chain.
See [IIFE (Immediately Invoked Function Expression)](#IIFE-(Immediately-Invoked-Function-Expression))
```javascript
// Closure - Multiple Counter
function Counter() {
let _count = 0; // private
return function() {
_count += 1;
return _count;
};
}
// counter refers to an anonimous inner function which is returned by Counter().
let counter = Counter();
// app.counter and app2.counter also refers to the same anonimous inner function.
let app = {counter: counter};
let app2 = {counter: counter};
console.log(app.counter()); //1
console.log(app.counter()); //2
console.log(app2.counter()); //3
console.log(counter()); //4
console.log(counter._count); // undefined - encapsulated
```
### 4. this binding
<u>**‘this’**, always references the owner of the function it is in</u>.
When ‘this’ is inside of an object’s method - the function’s owner is the object. Thus the ‘this’ keyword is bound to the object.
Yet when it is inside of a function, either stand alone or within another method, it will always refer to the window/global object.
* **In the global context**:
In the global execution context, ‘this’ points to the global object (window in Browser, global in Node).
* **In the function context**:
Function doesn’t have owner object. ‘this’ always points to the global object.
* **Inside of an object's method**:
When a function is called as a method of an object, its ‘this’ is set(bound) to the object, on which the method is called.
* **Inside a constructor**:
When a function is used as a constuctor (with the ‘new’ keyword), its ‘this’ is bound to the new object being constructed.
* **In arrow function**:
Arrow function doesn't bind ‘this’ to their own scope, ‘this’ refers to it’s current surrounding scope.
#### 4-1 Changing 'this' binding
##### 4-1-1. Call()
The **call()** method calls a function with a given this value and arguments provided individually.
```javascript
const bruce = {
name : 'Bruce'
};
const madeline = {
name : 'Madeline'
};
// this function is not bound to any object, but uses 'this'
function greet(){
return `Hello, I'm ${this.name}`;
};
greet(); // 'Hello, I'm undefined' - this is not bound to any object
greet.call(bruce) // 'Hello, I'm Bruce' - this is bound to bruce object
greet.call(madeline) // 'Hello, I'm Madeline' - this is bound to madeline object
```
##### 4-1-2. Apply()
The **apply()** is exactly same with call() except that arguments provided as an array (or an array-like object)
```javascript
// eg. 1
const arr = [2,3,-5,15,7];
// we pass null instead of this since Math.min() and max() doesn't use this
Math.min.apply(null, arr); // -5
Math.max.apply(null, arr); // 15
// eg. 2
update.apply(bruce, [1955, 'actor']);
/*
Now, bruce comes to
{
name : 'Bruce',
birthYear : 1955,
occupation : 'actor'
}
*/
```
##### 4-1-3. Bind()
The **bind()** creates and return a new function that has its 'this' set to the provided object while call() and apply() executes function and return the result value.
```javascript
let obj = {
prop: 'Hello',
sayHello: function() {
console.log( this.prop );
}
};
obj.sayHello(); // Logs "Hello"
// reference’s this refers to global object not obj
let reference = obj.sayHello;
reference(); // logs "undefined"
// bind() creates & return a new function that has its this set to the provided object
let newFunction = obj.sayHello.bind(obj);
newFunction(); // logs "Hello"
```
ES6 Features
---
### let, const
See [1-1. Variable Declaration](#1-1.-Variable-Declaration)
### Classes
See [2-3-2. Creating a Person object using Class](#2-3-2.-Creating-a-Person-object-using-Class)
Also, [3.2 Inheritance in ES6](#3.2-Inheritance-in-ES6)
### constuctor
The constructor method is a special method for creating and initializing an object created within a class.
It initializes an object when the class is instantiated.
A constructor can use the super keyword to call the constructor of a parent class.
If you do not specify a constructor method, a default constructor is used.
### super
Method that set the inheritance properties calling the father’s constructor. <u>The super must be in the first line of the constructor method</u>.
The super keyword can be used to access and call functions on an object's parent.
```javascript
super([arguments]); // calls the parent constructor.
super.functionOnParent([arguments]);
```
### new
See [4-1. Object.create() vs new (ES6)](#4-1.-Object.create()-vs-new-(ES6))
### static method
In JavaScript, **static method is added** not to class prototype object but **to class object** so that we can call the function with class object directrly.
```javascript
Student.staticMethod();
```
, which means, if we want to call static method, we need to use the constuctor property of prototype object.
```javascript
let ben = new Student(‘Ben Powers’, 20, ‘M’, 123456);
ben.constructor.staticMethod();
```
### arrow function
Arrow functions can't be used as a constructor.
We can **NOT** use the **‘new’** keyword with arrow function because **Arrow function never change its ‘this’ scope**. No 'this' binding allowed.
##### In my opinion, this characteristic is very useful in a sepecific situation. eg. when we pass the method as a parameter to other function.
> Syntax
> - If arrow function has only one argument, we can leave out parenthesis.
> - A single line without curly braces is returned implicitly.
```javascript
const fn = inputValue => inputValue + 1;
// is equivalent to
const fn = (inputValue) => {return inputValue + 1}
// '_' is a shorthand of '()', so this is also possible.
const fn = _ => console.log(‘Hi there!’);
```
### spread operator
See [4-3. Spread Operator (ES6)](#4-3.-Spread-Operator-(ES6))
Also, [4-4. Object.assign() vs Spread Operator](#4-4.-Object.assign()-vs-Spread-Operator)
### destructuring assignment
See [4-5. Destructuring Assignment](#4-5.-Destructuring-Assignment)
### for\.\.\.of
* **forEach** is an method that is <u>available only in Array objects</u>.
* The **for...in** statement <u>iterates over the enumerable properties of an object</u>, in an arbitrary order.
* The **for...of** statement <u>iterates over values of the **iterable object**</u>. So, it can iterate any objects that has **[Symbol.iterator]** including Array objects unless forEach
```javascript
// forEach
const arr = [1, 2, 3, 4, 5];
arr.forEach(item => { console.log(item); }); // 1 2 3 4 5
// for...in
const object = { a: 1, b: 2, c: 3 };
Object.prototype.foo = function() { return 0; };
for (const key in object) {
console.log(key, object[key]); // a 1 b 2 c 3 foo function()...
}
// for...of
const gen = function*() { yield 1; yield 2; yield 3; }; // generator
for (const value of gen()) {
console.log(value); // 1 2 3
}
```
### Iterator
In JavaScript an **iterator** is an object which defines a sequence and potentially a return value upon its termination. More specifically an iterator is <u>any object which implements the Iterator protocol by having a next() method</u>.
* **Iterator** has next() method and it follows below rules
> 1. it returns object with two properties: value and done.
> 2. when it reach to the end, it returns {done: true}
```javascript
// iterator
function makeRangeIterator(start = 0, end = Infinity, step = 1) {
let nextIndex = start;
let iterationCount = 0;
const rangeIterator = {
next: function() {
let result;
if (nextIndex < end) {
result = { value: nextIndex, done: false }
nextIndex += step;
iterationCount++;
return result;
}
return { value: iterationCount, done: true }
}
};
return rangeIterator;
}
// using the iterator
let it = makeRangeIterator(1, 10, 2);
let result = it.next();
while (!result.done) {
console.log(result.value); // 1 3 5 7 9
result = it.next();
}
console.log("Iterated over sequence of size: ", result.value);
// [5 numbers returned, that took interval in between: 0 to 10]
```
### Generator
**Generator** give us a concise way to implement iterator.
**Generator** is an **iterator object** since it has **next()** method follows rules.
additionally, it includes **return()** and **throw()** methods.
**Generator functions** are written using the **function\*** syntax. When called initially, generator functions do not execute any of their code, instead, **it returns a type of iterator called a Generator**.
if Generaotr.next() is called, generator function runs until it reach to **yield** keyword and return value.
if it can't meet **yield**, it returns {value: undefined, done: true}
```javascript
// generator function definition
function* makeRangeIterator(start = 0, end = 100, step = 1) {
for (let i = start; i < end; i += step) {
yield i;
}
}
// generator function returns Generator, which is an iterator object
const ge = makeRangeIterator(0, 10, 2);
for(const item of ge) {
console.log(item); // 0, 2, 4, 6, 8
}
```
### Iterable
* **Iterable** has a **[@@iterator]** method.
* **[@@iterator]** method is implemented by using **[Symbol.iterator]**.
* Object can have only one **[Symbole.iterator]**.
> #### Built-in iterables
> **Array**.prototype\[@@iterator]()
> **TypedArray**.prototype\[@@iterator]()
> **String**.prototype\[@@iterator]()
> **Map**.prototype\[@@iterator]()
> **Set**.prototype\[@@iterator]()
```javascript
// User-defined iterables
var myIterable = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
}
}
for (let value of myIterable) {
console.log(value); // 1, 2, 3
}
// or
[...myIterable]; // [1, 2, 3]
```
### Set, WeakSet
#### Array
* Contains whatever value you push
* **Difficult to delete** a particular element
* map(), reduce(), filter(), shift(), unshift(), pop(), push(), join(),...
#### Set
* Contains only **unique values**
* Easy to delete a value
* **Better API set**: add(), has(), delete(), and clear()
```Javascript
# Create an array with unique values using the "Set" object
# You could try writing a "map" or "filter" to achieve this.
const arrayWithUniqueItems = [...new Set([1, 2, 3, 3,])]
// [1, 2, 3]
```
#### WeakSet
* Contains **only objects** (no primitive variables available)
* No .forEach() to iterate
* **If an element object has no other reference left, it will be auto released to garbage colletor**
* In terms of resource management, WeaSet has an advantage.
### Map, WeakMap
#### Plain Object
* The keys can only be **String** or **Symbol**
* **Not iterable**
* **Difficult to get size**
* Key conflicts may occur
#### Map
* Accepts **anything as key** (even NaN)
* **Better API set**: get(), set(), clear(), and .size()
* **Iterable**: ‘forEach’ and ‘for of’ available
* If you focus on iterating, map will give you better performance.
#### WeakMap
* **Key** must be of **Object** (not null)
* No .forEach() to iterate
* If a key object is deleted, the value assigned against that key will also be destoyed.
### Template literals
Template literals are enclosed by the back-tick (`)
```javascript
console.log(`Hello ${name}!`);
```
### import\.\.\.from, export
It replaces require() and model.exports of Node.js
### Object.is
#### Equality comparisons and sameness
* **double equals** (==) will **perform a type conversion** when comparing two things
* **triple equals** (===) will do the same comparison as double equals but **without type conversion**
* **Object.is** does **no type conversion** and **no special handling for NaN, -0, and +0**.
ES7 Features
---
### Promise
The **Promise** object represents the eventual completion with success value (or failure reason) of an asynchronous operation.
Using promise, we can avoid nesting callbacks that keeps getting indented to indented.
#### What we can do with Promise?
* Sequential asyncronous programming with blocking I/O (**Promise.then**)
* Concurrent programming (**Promise.all** or **Promise.race**)
* Catching all errors in the chain with a single function (**Promise.catch**)
#### Promise Object
__proto__
.constuctor()
.then()
.catch()
.finally()
Symbol: “Promise”
[[PromiseStatus]] // status (resolved or rejected)
[[PromiseValue]] // result Object
#### Promise state transition
<img src="https://drive.google.com/uc?export=view&id=1py4b94fbOPV13qy_QDm0jYEu6VUKuzj_" alt="s-expression transform" width="800"/>
#### Executor function
The executor function is executed immediately by the Promise implementation, passing resolve and reject functions.
<u>The executor normally initiates some asynchronous work (**pending** state)</u>, and then, once that completes, <u>either calls the resolve function (**fulfilled** state)</u> to resolve the promise <u>or the reject function (**rejected** state)</u> to handle the error.
If an error is thrown in the executor function, the promise is rejected. The return value of the executor is ignored
#### Promise methods
* **Promise.resolve()** method returns a Promise object that is resolved with a given value.
So, if we just want to run some routine asyncronously with particular object as input data without any changes, we can call Promise.resolve(obj) simply instead of passing executor function into Promise()
* **Promise.then()** method returns a Promise. It takes up to two arguments: callback functions for the success as an onFulfilled() and failure cases of the Promise as an onRejected().
Once a Promise is fulfilled or rejected, the respective handler function (onFulfilled or onRejected) will be called asynchronously.
* **Promise.catch()** method returns a Promise and deals with rejected cases only.
* **Promise.finally()** method returns a Promise. When the promise is settled, i.e either fulfilled or rejected, the specified callback function (final routine) is executed.
* **Promise.all()** method returns a single Promise that resolves when all of the promises passed as an iterable have resolved or when the iterable contains no promises.
There is no implied ordering in the execution of the array of Promises given. On some computers, they may be executed in parallel, or in some sense concurrently, while on others they may be executed serially. For this reason, there must be no dependency in any Promise on the order of execution of the Promises.
#### Asyncronous programming with Promise
```javascript
const tick = Date.now();
const log = v => console.log(`${v} \t (Elapsed: ${Date.now() - tick})`);
const codeBlocker = v => {
let i = 0;
while(i < 100000000) {i++;}
return v;
}
const codeBlocker2 = v => {
return new Promise((resolve, reject) => {
let i = 0;
// this while loop is still blocking on the main thread.
// because this executor function is executed immediately.
while(i < 100000000) {i++;}
resolve(v);
});
}
// so to ensure that all of our synchronous code runs as fast as possible,
// we'll refactor our code once again to say promise resolve,
// then we'll run the while loop inside of that result promises callback
const codeBlocker3 = v => {
// by putting this code inside of resolved promise,
// we can be guaranteed that it will be executed after all the synchronous code
return Promise.resolve(v).then(v => {
let i = 0;
while(i < 100000000) {i++;}
return v;
});
}
log('🍞 Synchronous 1');
log(codeBlocker('🐷 many loops done from blocker #1'));
codeBlocker2('🐷 many loops done from blocker #2').then(log);
codeBlocker3('🐷 many loops done from blocker #3').then(log);
log('🍞 Synchronous 2');
```
> **Result**
🍞 Synchronous 1 (Elapsed: 0)
🐷 many loops done from blocker #1 (Elapsed: 148) // loop ran syncronously and logged syncronously
🍞 Synchronous 2 (Elapsed: 265) // blocker #1 + blocker #2
🐷 many loops done from blocker #2 (Elapsed: 266) // loop ran syncronously but logged asyncronously
🐷 many loops done from blocker #3 (Elapsed: 363) // loop ran asyncronously
#### Concurrent programming with Promise
> **Promise.all() vs Promise.race()**
> **Promise.all()** waits all promises' resolved or rejected values whereas **Promise.race()** only takes only resolved or rejected value of the first completed promise.
```javascript
/** Concurrent Programming
* We could get both of these things at the same time
*/
const makeSmoothieConcurrent = async () => {
const a = getAsyncFruit('concurrent', 'pineapple');
const b = getAsyncFruit('concurrent', 'strawberry');
// here, we've doubled the speed of the original function
const smmothie = Promise.all([a, b, 'concurrent smmothie']);
return smmothie;
}
```
ES8 Features
---
### Async, Await
**Promises** are a huge improvement over callbacks but promises can still be really hard to read and follow especially when you have a long chain of multiple asynchronous events.
**async**, **await** really just boils down to syntactic sugar to <u>make your asynchronous code read like synchronous code</u>. We can replace a long chain of Promises to handle multiple asynchronous events.
```javascript
// both functions are exactly same.
const fn_promise = obj => Promise.resolve(obj);
const fn_async = async obj => obj;
```
```javascript
/**
* One of the most annoying things with promises is
* that it's kind of difficult to share result values
* bretween multiple steps in the promise chain.
*/
const makeSmoothiePromise = () => {
let a;
return getAsyncFruit('promise', 'pineapple')
.then(v => {
a = v;
return getAsyncFruit('promise', 'strawberry');
})
.then(v => [a, v, 'promise smoothie']);
}
// But async/await solves this problem really nicely
const makeSmoothieAsync = async () => {
// we're waiting for a pineapple to resolve
const a = await getAsyncFruit('async', 'pineapple');
// and then we're getting a strawberry afterwards
const b = await getAsyncFruit('async', 'strawberry');
return [a, b, 'async smoothie'];
}
```
Advanced Topics
---
### Enhanced object literals
ES6 enhanced object literals brings three sweet upgrades to the objects you know and love. They are:
1. Property value shorthands
2. Method shorthands
3. The ability to use computed property names
#### 1. Property value shorthands
In case you assign a variable that has the same name as an object property.
You could write this in a shorter way in ES6.
```javascript
const fullName = 'Zell Liew'
// ES6 way
const Zell = {
fullName
}
// Underneath the hood, ES6 does this:
const Zell = {
fullName: fullName
}
```
#### 2. Method shorthands
With ES6, we get to write methods with a shorthand. We can remove **: function** from a method declaration and it will work like it used to:
```javascript
const anObject = {
// ES6 way
aShorthandMethod (arg1, arg2) {},
// ES5 way
aLonghandMethod: function (arg1, arg2) {},
}
```
#### 3. Computed object property names
In the old JavaScript way, you’d have to create the object, then assign your property to in, like this:
```javascript
// ES5
const newPropertyName = 'smile'
// Create an object first
const anObject = { aProperty: 'a value' }
// Then assign the property
anObject[newPropertyName] = ':D'
// Adding a slightly different property and assigning it
anObject['bigger ' + newPropertyName] = 'XD'
// Result
// {
// aProperty: 'a value',
// 'bigger smile': 'XD'
// smile: ':D',
// }
```
In ES6, you no longer need to do this roundabout way. You can assign dynamic property names directly when creating your object. The key is to enclose the dynamic property with square brackets:
```javascript
const newPropertyName = 'smile'
// ES6 way.
const anObject = {
aProperty: 'a value',
// Dynamic property names!
[newPropertyName]: ':D',
['bigger ' + newPropertyName]: 'XD',
}
// Result
// {
// aProperty: 'a value',
// 'bigger smile': 'XD'
// smile: ':D',
// }
```
This syntax allows to create a new object with dynamic property:
```javascript
onChange = (evt) => {
this.setState({ [evt.target.name]: evt.target.value })
}
```
### IIFE (Immediately Invoked Function Expression)
It’s a function that runs as soon as it is defined.
It is a design pattern which is also known as a Self-Executing Anonymous Function and contains two major parts.
* The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope.
* The second part creates the immediately executing function expression () through which the JavaScript engine will directly interpret the function.
```javascript
// Creating Closure by using IIFE and Arrow function
let counter = (function () {
let _count = 0; // private
// Closure access variables through its lexical scope
// So, it doesn't need 'this' to access variables,
// which means we can return arrow function as a closure
return () => ++_count;
})(); // IIFE
let app = {
counter: counter
};
let app2 = {
counter: counter
};
console.log(app.counter()); //1
console.log(app.counter()); //2
console.log(app2.counter()); //3
```
### Functional Programming in Javascript
Functional programming is a process to make software by combining pure functions while avoiding shared state, mutable data, and side-effects.
#### Characteristics:
* declarative (not imperative)
* HOF (Higher Order Function)
* Currying
* Function Composition
#### 1. Pure and Impure function
**Pure function**: when it gets the same input, always returns the same output. It has no side-effect and **is not affected by outer environment**.
**Pros**: Immune to outside bugs and it makes code refactoring and reconstructing easy
```javascript
function add(a,b){return a + b} // pure
function add(a,b){return a + b + c} // impure
var obj = {val : 10}
function add(obj, b){ return { val: obj.val + b } } // pure
function add(obj, b){ obj.val += b } // impure
```
* **Immutability** - instead of modifying input parameter, we create a copy of input parameter and manipulate and returns the copy, so that input argument can be immutable and function can be free to side effects of sharing data
#### 2. Higher Order Function (HOF)
**Higher-order function** is a function that meets the following:
* takes a function as argument.
* returns a function as its result.
```javascript
/* Higher Order Function */
const calc = (num1, num2, op) => op(num1, num2);
const add = (num1, num2) => num1 + num2;
const multiply = (num1, num2) => num1 * num2;
const power = (num1, num2) => Math.pow(num1, num2)
calc(2, 3, add) // 5
calc(2, 3, multiply) // 6
calc(2, 3, power) // 8
```
* **First-class citizens/object**
In programming languages, **when you are able to pass, return and assign a type, that type is considered to be a first class citizen**.
This is one reason Javascript is becoming a popular destination for functional programming. Since we are able to create functions that can accept functions as well as return functions. This allows us to create Higher Order Functions. Higher Order Functions are functions that accept a function, and/or return a function.
#### 3. Currying
**Currying** makes logic more plentiful and reduces code, such as creating a function that is partially applied when all factors are not prepared or handing it over to another function as a factor.
```javascript
/* currying */
const add_curry = (num1) => (num2) => num1 + num2;
const add2 = add_curry(2); // creating a function that is partially applied
add2(5); // 7
add_curry(3)(5) // 8
/* Higher Order Function with Currying*/
const calcWith2 = (op) => (num) => op(2, num);
const add = (num1, num2) => num1 + num2;
const multiply = (num1, num2) => num1 * num2;
const add2 = calcWith2(add);
const multiply2 = calcWith2(multiply);
add2(3); // 5
multiply2(3) // 6
```
#### **connect()** method of **redux** is a good example of **currying** and **HOF**
```javascript
import { connect } from "react-redux";
import { PersonComponent } from "./person";
const mapStateToProps = state => ({
name: state.name,
age: state.age
});
const mapDispatchToProps = {
setName: name => {
type: "SET_NAME", name;
},
setAge: age => {
type: "SET_AGE", age;
}
};
// create HOC
const connectHOC = connect(
mapStateToProps,
mapDispatchToProps
);
//It returns a new HOC mapping input state and dispatch from given Component
const ConnectedComponent = connectHOC(PersonComponent);
// is equals to
const ConnectedComponent = connect(mapStateToProps, mapDispatchToProps)(PersonComponent);
```
#### 4. Function Composition
References
---
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript)
* [Introduction to commonly used ES6 features](https://zellwk.com/blog/es6/)
###### tags: `Language` `Document`