Part 2

Classes

Classes

  • Can be seen as a next step from Module Pattern
     
  • Special JavaScript functions
     
  • Can be declared as expression or declaration
     
  • Class name start with a capital

What's inside a Class

  • constructor
     
  • getter & setter
     
  • methods
     
  • static methods (can't be called from other methods in the Class itself)

Class decleration

class Rectangle {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }

    getHeight() {
        return this.height;
    }

    getWidth() {
        return this.width;
    }
}

Constructor

class Rectangle {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }

    getHeight() {
        return this.height;
    }

    getWidth() {
        return this.width;
    }
}

Special method that is creating and initializing an object created with a Class.

Class expression

// unnamed class expression
var Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

// named class expression
var Rectangle = class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

Use a Class

var bigRectangle = new Rectangle(50, 50);

bigRectangle.getHeight(); // Output: 50
bigRectangle.getWidth(); // Output: 50

Extending a Class

class Square extends Rectangle {
    constructor(length) {
        super(length, length);
    }
    
    area() {
        return this.width * this.height
    }
    
}
var bigRectangle = new Square(100);

bigRectangle.area(); // Output: 1000
bigRectangle.getHeight(); // Output: 100
bigRectangle.getWidth(); // Output: 100

Use the super method to access the extended class.

Class methods

class Rectangle {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }

    getHeight() {
        return this.height;
    }

    getWidth() {
        return this.width;
    }

    get widthAndHeight() {
        return {
            width: this.width,
            height: this.height
        }
    }

    set setHeightAndWidth(sizeObject) {
        this.width = sizeObject.width,
        this.height = sizeObject.height
    }
}

Use class methods

var bigRectangle = new Rectangle(100, 200);

bigRectangle.getHeight(); 
// Output: 200

bigRectangle.getWidth(); 
// Output: 100

bigRectangle.height; 
// Output: 200

bigRectangle.width; 
// Output: 100

bigRectangle.widthAndHeight(); 
// Output: bigRectangle.widthAndHeight is not a function

bigRectangle.widthAndHeight; 
// Output: {width: 200, height: 100}

bigRectangle.setWidth({width: 450, height: 50}) 
// Output: bigRectangle.setWidth is not a function

bigRectangle.setHeightAndWidth = {width: 450, height: 50};

bigRectangle; 
// Output: {width: 450, height: 50}

Map

Map

  • A special Object
     
  • Can store key-value pairs
     
  • Is iterable (a normal Object isn't)

Map property & methods

  • size: returns number of values
  • set(): Adds value to a map Object
  • delete(): Removes value from a map Object
  • clear(): Removes all elements from a map Object
  • entries(): returns a Array with all the [key, value]
  • forEach(): iterate over all the values
  • has(): returns if a value is in the map Object or not
  • values(): returns a iterator Object that contains all the values for each item in the map Object.
  • keys(): returns a iterator Object that contains all the keys for each item in the map Object.

Define map Object

const testMap = new Map();

set()

const testMap = new Map();

testMap.set(0, true);
testMap.set(1, false);
testMap.set(2, 'This is my test map');

// Map(3) {0 => true, 1 => false, 2 => "This is my test map"}

delete()

// Map(3) {0 => true, 1 => false, 2 => "This is my test map"}

testMap.delete(0);
// Returns true, because it successfully

testMap.delete(4);
// Returns false, because there was no item 4

testMap
// Map(2) {1 => false, 2 => "This is my test map"}

clear()

// Map(3) {0 => true, 1 => false, 2 => "This is my test map"}

testMap.clear();
// Map(0) {}

entries()

// Map(3) {0 => true, 1 => false, 2 => "This is my test map"}

testMap.entries();
// MapIterator {0 => true, 1 => false, 2 => "This is my test map"}

for([key, value] of testMap.entries()) {
	console.log('Key: ' + key + ': ' + value);
}

// Key: 0: true
// Key: 1: false
// Key: 2: This is my test map

forEach()

// Map(3) {0 => true, 1 => false, 2 => "This is my test map"}

testMap.forEach(item => {
	console.log('Item: ', item);
})

// Item:  true
// Item:  false
// Item:  This is my test map

has()

const testSet = new Map();

testSet.set(0, 'First');
testSet.set(1, 'Second');
testSet.set(2, 'Third');

testSet.has(1);
// Output: true

testSet.has(3);
// Output: false

value()

const testSet = new Map();

testSet.set(0, 'First');
testSet.set(1, 'Second');
testSet.set(2, 'Third');

for(item of testSet.values()) {
    console.log('Item: ', item);
}

// Item: First
// Item: Second
// Item: Third

keys()

const testSet = new Map();

testSet.set(0, 'First');
testSet.set(1, 'Second');
testSet.set(2, 'Third');

for(item of testSet.keys()) {
    console.log('Item: ', item);
}

// Item: 0
// Item: 1
// Item: 2

Set

Set

  • A special Object
     
  • Can store only unique values and Object references
     
  • You can iterate through the elements of a set Object

Set property & methods

  • size: returns number of values
  • add(): Adds value to a set Object
  • delete(): Removes value from a set Object
  • clear(): Removes all elements from a set Object
  • entries(): returns a Array with all the [value, value]
  • forEach(): iterate over all the values
  • has(value): returns if a value is in the set Object or not
  • values(): returns a iterator Object that contains all the values for each item in the set Object.
  • keys(): is the same like values()

Define set Object

const numbersSet = new Set([1,2,3,4,5]);
// returns: Set(5) {1, 2, 3, 4, 5}

const stringSet = new Set(['Jan', 'Rick', 'Pieter', 'Tim']);
// returns: Set(4) {"Jan", "Rick", "Pieter", "Tim"}

const objectSet = new Set([{a: 1, b: 2}]);
// returns: Set(1) {a: 1, b: 2}

const arraySet = new Set([['javascript', 'coffeescript'], ['css', 'sass']]);
// returns: Set(2) {['javascript', 'coffeescript'], ['css', 'sass']}

add()

const newSetObject = new Set();
newSetObject.add('Raymon');
newSetObject.add({a: 1, b: 2});
newSetObject.add(1).add(2).add(3).add(4).add(5)

// returns: Set(7) {"Raymon", {a: 1, b: 2}, 1, 2, 3, 4, 5}

delete()

const newSetObject = new Set();
newSetObject.add('Raymon');
newSetObject.add({a: 1, b: 2});
newSetObject.add(1).add(2).add(3).add(4).add(5)

// returns: Set(7) {"Raymon", {a: 1, b: 2}, 1, 2, 3, 4, 5}

newSetObject.delete(3)

// returns: Set(6) {"Raymon", {a: 1, b: 2}, 1, 2, 4, 5}

size

const numbersSet = new Set([1,2,3,4,5]);
numberSet.size; // returns: 5

const stringSet = new Set(['Jan', 'Rick', 'Pieter', 'Tim']);
numberSet.size; // returns: 4

const objectSet = new Set([{a: 1, b: 2}]);
numberSet.size; // returns: 1

const arraySet = new Set([['javascript', 'coffeescript'], ['css', 'sass']]);
numberSet.size; // returns: 2

clear()

const arraySet = new Set([['javascript', 'coffeescript'], ['css', 'sass']]);
// returns: Set(2) {['javascript', 'coffeescript'], ['css', 'sass']}
arraySet.clear();
// Set(0) { }

forEach()

const arraySet = new Set([['javascript', 'coffeescript'], ['css', 'sass']]);
// returns: Set(2) {['javascript', 'coffeescript'], ['css', 'sass']}
arraySet.forEach(item => {
    console.log('item: ', item);
})

// item:  (2) ["javascript", "coffeescript"]
//item:  (2) ["css", "sass"]

entries()

const objectSet = new Set([{a: 1, b: 2}, {a: 3, b: 4}]);
for (let [key, value] of objectSet.entries())  {
    console.log(key);
}

// {a: 1, b: 2}
// {a: 3, b: 4}

keys()

const objectSet = new Set([{a: 1, b: 2}, {a: 3, b: 4}]);
for (let key of objectSet.keys())  {
    console.log(key);
}

// {a: 1, b: 2}
// {a: 3, b: 4}

values()

const objectSet = new Set([{a: 1, b: 2}, {a: 3, b: 4}]);
for (let value of objectSet.values())  {
    console.log(value);
}

// {a: 1, b: 2}
// {a: 3, b: 4}

has()

const objectSet = new Set([{a: 1, b: 2}, {a: 3, b: 4}]);
objectSet.has({a: 1, b: 2})
// false
const stringSet = new Set(['Jan', 'Rick', 'Pieter', 'Tim']);
stringSet('Jan')
// true
const objectFirst = {a: 1, b: 2};
const objectSecond = {a: 3, b: 4};
const objectSet = new Set([objectFirst, objectSecond]);
objectSet.has(objectFirst)
// true
objectSet.has({a: 1, b: 2})
// false

Fetch

Fetch

  • A modern way of doing AJAX requests
     
  • Replacement of the XMLHttpRequest
     
  • Works with Promises
     
  • Won't be rejected by an HTTP 404 or 500
     
  • Won't send or receive cookies from the server by default.

A basic fetch

get request

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

How fetch works

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

By default a GET request

When the Promise is resolved we get the JSON body of the response

After that we get the JSON body of the response

Fetch options

const postOptions = {
    method: "POST", // *GET, POST, PUT, DELETE, etc.
    mode: "cors", // no-cors, cors, *same-origin
    cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
    credentials: "same-origin", // include, same-origin, *omit
    headers: {
        "Content-Type": "application/json; charset=utf-8",
        // "Content-Type": "application/x-www-form-urlencoded",
    },
    redirect: "follow", // manual, *follow, error
    referrer: "no-referrer", // no-referrer, *client
    body: JSON.stringify(data), // body data type must match "Content-Type" header
}

const myRequest = new Request('http://example.com/movies.json', postOptions);

fetch(myRequest)
    .then(function(response) {
        return response.json();
    })
    .then(function(myJson) {
        console.log(myJson);
    });

Fetch methods

  • POST
  • GET
  • PUT
  • DELETE

Fetch modes

  • cors
  • no-cors
  • same-origin

Fetch cache

  • no-cache
  • reload
  • force-cache
  • only-if-cached

Fetch credentials

  • include
  • same-origin

Fetch headers

  • content-type
  • Auth

Fetch redirect

  • manual
  • error

Fetch referrer

  • manual
  • error

Fetch body

This includes all the data.

For example the JSON of a Form

Destructuring​

Destructuring

Is a convenient way of extracting data from Arrays and Objects.

Destructuring

Arrays

const names = ['Luke', 'Eva', 'Phil'];

const [first] = names;

console.log('First: ', first); // 'Luke'

Make a variable for the first value

Destructuring

const names = ['Luke', 'Eva', 'Phil'];

const [first, second, third] = names;

console.log('First: ', first); // 'Luke'
console.log('Second: ', second); // 'Eva'
console.log('Third: ', third); // 'Phil'

Make a variable for the first, second and third value

Destructuring

const names = ['Luke', 'Eva', 'Phil'];

const [first, second, third, fourth] = names;

console.log('First: ', first); // 'Luke'
console.log('Second: ', second); // 'Eva'
console.log('Third: ', third); // 'Phil'
console.log('Fourth: ', fourth); // undefined

Missing values

Destructuring

Giving default values to missing elements

const names = ['Luke', 'Eva', 'Phil'];

const [first, second, third, fourth = 'Martin'] = names;

console.log('First: ', first); // 'Luke'
console.log('Second: ', second); // 'Eva'
console.log('Third: ', third); // 'Phil'
console.log('Fourth: ', fourth); // 'Martin'

Destructuring

Skipping values

const names = ['Luke', 'Eva', 'Phil'];

const [first, , second] = names;

console.log('First: ', first); // 'Luke'
console.log('Second: ', second); // 'Phil'

Destructuring

Assign the rest of an Array to a variable

const names = ['Luke', 'Eva', 'Phil'];

const [first, ...rest] = names;

console.log('First: ', first); // 'Luke'
console.log('Rest: ', rest); // ['Eva', 'Phil']

Destructuring

Destructuring

Objects

const person = {  
  name: 'Luke',
  age: '24',
  facts: {
    hobby: 'Photo',
    work: 'Software Developer'
  }
}

const {name, age} = person;  
console.log(name, age); // 'Luke' '24' 

Getting data from an Object

Destructuring

const person = {  
  name: 'Luke',
  age: '24',
  facts: {
    hobby: 'Photo',
    work: 'Software Developer'
  }
}

const {facts: hobby} = person;  
console.log(hobby); // 'Photo' 

Getting nested data from an Object

Destructuring

const person = {  
  name: 'Luke',
  age: '24',
  facts: {
    hobby: 'Photo',
    work: 'Software Developer'
  }
}

const {hometown = 'Unknown'} = person;  
console.log(hometown); // 'Unknown' 

Default values when data is missing

Destructuring

const person = {  
  name: 'Luke',
  age: '24',
  facts: {
    hobby: 'Photo',
    work: 'Software Developer'
  }
}

const nameAndAge = ({name, age}) => {  
  return `${name} is ${age} years old`;
}

console.log(nameAndAge(person)); // Luke is 24 years old  

Destructuring as a function parameter

Destructuring

const { Loader, main } = require('toolkit/loader');

Module loading

Destructuring

For-of loop

For-of loop

The for...of statement creates a loop iterating over iterable objects (including the built-in String, Array, e.g. the Array-like arguments or NodeList objects, TypedArray, Map and Set)

let iterable = [10, 20, 30];

for (let value of iterable) {
  value += 1;
  console.log(value);
}
// 11
// 21
// 31

For-of loop

Loop over Array

let iterable = 'boo';

for (let value of iterable) {
  console.log(value);
}
// "b"
// "o"
// "o"

For-of loop

Loop over String

let iterable = new Map([['a', 1], ['b', 2], ['c', 3]]);

for (let entry of iterable) {
  console.log(entry);
}
// ['a', 1]
// ['b', 2]
// ['c', 3]

for (let [key, value] of iterable) {
  console.log(value);
}
// 1
// 2
// 3

For-of loop

Loop over Map

function exampleFunction() {
  for (let argument of arguments) {
    console.log(argument);
  }
};

exampleFunction(1, 2, 3);

// 1
// 2
// 3

For-of loop

Loop over arguments

let articleParagraphs = document.querySelectorAll('article > p');

for (let paragraph of articleParagraphs) {
  paragraph.classList.add('read');
}

For-of loop

Loop over DOM collection / NodeList

For-in loop

For-in loop

The for...in statement iterates over all non-Symbol, enumerable properties of an object.

For-in loop

The for...in statement iterates over all non-Symbol, the properties you added to a Object or Array (enumerable properties) of an Object or Array.

 

Enumerable properties are the properties you added to a Object or Array. So you can't iterate over build in methods.

var obj = {a: 1, b: 2, c: 3};
    
for (const prop in obj) {
  console.log(`${prop}`);
}

// Output:
// a
// b 
// c

For-in loop

Loop over Object properties

let articleParagraphs = document.querySelectorAll('article > p');

for (let paragraph of articleParagraphs) {
  paragraph.classList.add('read');
}

For-in loop

Loop over DOM collection / NodeList

Generators

Generators

A generator is a special type of function that can be entered and exited a number of times.

 

Best described as, “a function that can be paused”.

Generators

function* idMaker() {
  var index = 0;
  while (index < index+1)
    yield index++;
}

var gen = idMaker();

console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3

Generators

Let's build a ID generator

const foo = function* () {
  yield 10;
  yield 20;
};

const bar = foo();
console.log(bar.next()); // {value: 10, done: false}
console.log(bar.next()); // {value: 20, done: false}
console.log(bar.next()); // {value: undefined, done: true}

Generators

Generator defined in an expression

Modules

Modules

Native JavaScript modules.

// exports a function declared earlier
export { myFunction }; 

function myFunction() {}

Modules

We create modules with the export keyword

export default function() {}

Modules

Export a default function

export default class {}

Modules

Export a default Class

// exports a constant
export const foo = Math.sqrt(2);

export function bar = Math.random();

Modules

Export a named function 

// Module bar
export function bar = Math.random();

Modules

Import a named module

// Module foo
import { bar } from 'bar.js';

export const foo = function() {
    return bar;
}
// Module bar
export default function () {
    return Math.random();
}

Modules

Import a default module

// Module foo
import bar from 'bar.js';

export const foo = function() {
    return bar();
}
// Module bar
export default function () {
    return Math.round();
}

export const random = function() {
    return Math.random();
}

Modules

Import a default and named modules

// Module foo
import defaultBar, { random } from 'bar.js';

export const foo = function() {
    return defaultBar();
}

JavaScript (ES6) - Part 2

By CodePamoja

JavaScript (ES6) - Part 2

  • 84