class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
getHeight() {
return this.height;
}
getWidth() {
return this.width;
}
}
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.
// 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;
}
}
var bigRectangle = new Rectangle(50, 50);
bigRectangle.getHeight(); // Output: 50
bigRectangle.getWidth(); // Output: 50
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 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
}
}
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}
const testMap = new Map();
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"}
// 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"}
// Map(3) {0 => true, 1 => false, 2 => "This is my test map"}
testMap.clear();
// Map(0) {}
// 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
// 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
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
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
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
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']}
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}
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}
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
const arraySet = new Set([['javascript', 'coffeescript'], ['css', 'sass']]);
// returns: Set(2) {['javascript', 'coffeescript'], ['css', 'sass']}
arraySet.clear();
// Set(0) { }
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"]
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}
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}
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}
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('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
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
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);
});
This includes all the data.
For example the JSON of a Form
Is a convenient way of extracting data from Arrays and Objects.
Arrays
const names = ['Luke', 'Eva', 'Phil'];
const [first] = names;
console.log('First: ', first); // 'Luke'
Make a variable for the first value
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
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
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'
Skipping values
const names = ['Luke', 'Eva', 'Phil'];
const [first, , second] = names;
console.log('First: ', first); // 'Luke'
console.log('Second: ', second); // 'Phil'
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']
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
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
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
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
const { Loader, main } = require('toolkit/loader');
Module loading
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
Loop over Array
let iterable = 'boo';
for (let value of iterable) {
console.log(value);
}
// "b"
// "o"
// "o"
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
Loop over Map
function exampleFunction() {
for (let argument of arguments) {
console.log(argument);
}
};
exampleFunction(1, 2, 3);
// 1
// 2
// 3
Loop over arguments
let articleParagraphs = document.querySelectorAll('article > p');
for (let paragraph of articleParagraphs) {
paragraph.classList.add('read');
}
Loop over DOM collection / NodeList
The for...in statement iterates over all non-Symbol, enumerable properties of an object.
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
Loop over Object properties
let articleParagraphs = document.querySelectorAll('article > p');
for (let paragraph of articleParagraphs) {
paragraph.classList.add('read');
}
Loop over DOM collection / NodeList
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”.
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
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}
Generator defined in an expression
Native JavaScript modules.
// exports a function declared earlier
export { myFunction };
function myFunction() {}
We create modules with the export keyword
export default function() {}
Export a default function
export default class {}
Export a default Class
// exports a constant
export const foo = Math.sqrt(2);
export function bar = Math.random();
Export a named function
// Module bar
export function bar = Math.random();
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();
}
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();
}
Import a default and named modules
// Module foo
import defaultBar, { random } from 'bar.js';
export const foo = function() {
return defaultBar();
}