1 of 34

6 - Advanced JavaScript.

Speck Academy 2021

2 of 34

Objects

Callback functions

Promises

ES6+ features

1

2

3

4

Overview

3 of 34

1

Objects

4 of 34

Objects

JavaScript is designed on a simple object-based paradigm.

  • An object is a collection of properties, and a property is an association between a name (or key) and a value.
  • A property's value can be a function, in which case the property is known as a method.
  • In addition to objects that are predefined in the browser, you can define your own objects.

Objects in JavaScript, just as in many other programming languages, can be compared to objects in real life.

5 of 34

Objects

In JavaScript there are few popular ways of creating objects, and each has its own special features:

  • Object initializers (literal notation): delivers single object, an object can’t be instantiated into multiple instances (missing constructor).
  • Constructor function: with constructor function notation object that is created can be instantiated into multiple instances. Better code optimization and organization compared to the object initializers.
  • Class (ES6+): this is syntactic sugar for constructor function which allows us to create objects more efficiently with the syntax that is similar to the other class-based programming languages (but still JavaScript creates those objects on prototype-based object model).

6 of 34

Objects

Object is created with object literals notation:

  • Object consists of properties and one method.
  • If we want to reference object property inside the method, we must use “this” keyword.
  • It’s not possible to instantiate new object from existing object (take a look at line 22). At line 22 only reference to “vehicle” object is created, this means if we modify any of “vehicle2” properties, this changes will propagate to the “vehicle” object also, and vice-versa.

7 of 34

Objects

  • If we want to instantiate new object, we should create another object with literals notation (code repetition).
  • Use object literals notation only if instantiation of multiple objects is not needed.
  • Notice that we’ve used shorthand notation for method definition inside “vehicle2” object.
  • If we want to instantiate multiple objects from one specific object, we should use constructor function or Class syntax.

8 of 34

Objects

Object is created with constructor function:

  • Use capital initial letter for constructor function.
  • Create a new instance of the object with “new” keyword.
  • Multiple instances can be created easily.
  • Object inheritance is possible.
  • Properties can be stored inside prototype object. However, in this example, method isn’t stored inside prototype object (we should use different approach).

9 of 34

Objects

  • Methods are stored inside prototype object because we declared our methods on the prototype object.
  • Car and Boat objects inherit the properties and constructor from Vehicle object (line 19 & 27).
  • Car and Boat inherit the method from Vehicle prototype object (line 24 & 30).
  • Now we can instantiate Car and Boat objects and work with them inside our App (line 33 & 34).
  • It seems that code is a bit untidy, but soon we’ll see how we can improve this with ES6+ syntactic sugar (Class syntax).

10 of 34

Objects

Difference between method that is stored inside prototype object and one that is attached directly to their object.

  • In the example above, method is stored in the prototype object of Vehicle.
  • In the example below method “getSummary” is stored inside the Car object.
  • When method is stored/attached to the prototype object, code will be more efficient.

11 of 34

Objects

Object is created with class syntactic sugar:

  • We can create objects with the new syntax from ES6+ and our code will be tidier.
  • JavaScript is still prototype-based language (class keyword won’t change JavaScript to the class-based language).
  • This syntax just creates everything shown in the constructor function automatically (take a look at slide 9).
  • Read comments in the code for better understanding of class, extends, constructor() and super().

12 of 34

2

Callback functions

13 of 34

Callback functions

Let’s remember what we said last time about the callback functions:

  • A callback function is a function that is passed into another function as an argument.
  • A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed.
  • It’s the combination of these two that allow us to extend our functionality.

14 of 34

Callback functions

Result of code from the previous slide will be like it’s shown in the screenshot below!

  • With callback function we can define specific behaviour when some other function finishes their process.
  • In our example one anonymous callback function is passed into processOrder function, and another anonymous function into setTimeout function.
  • Callback functions come in handy when we want to achieve asynchronous behaviour of code execution.

15 of 34

Callback functions

Let’s look another example (house building) where we want to continue with our code only when the previous process is done.

  • When foundations are ready, then build the walls. When walls are ready, then build the roof.
  • In this example we are nesting our functions and something called callback hell occurred. This code is ok, but we can write this in more elegant way with Promises.

16 of 34

3

Promises

17 of 34

Promises

Objects that represent the eventual completion or failure of asynchronous operation, and its resulting value. Generally used for easier handling of asynchronous operations such as file operations, API calls, DB calls, IO calls...

Promise can be created like it is shown in the code below.

The constructor accepts a function called executor which accepts two parameters resolve and reject. resolve() function should be executed when expected result is returned, and reject() in case when unexpected error occured.

18 of 34

Promises

Code from slide 15 (callback hell), now can be rewritten with promises:

  • Part of code from line 10 to 17 now is wrapped with the Promise object. We don’t need callback function in the list of arguments of buildSomething function expression because Promise has its own resolve and reject method.
  • We can chain code with then, but in order to do that successfully, we must return new function expression call of buildSomething.

19 of 34

Promises

In example on the right side, two promises are created. Each promise resolves after specific time expires.

By use of then() we can handle the promise and get the result of execution. With catch() we can handle errors, and finally() is always executed.

Promises also can be handled in the way that we want to wait until all promises resolve.

Try this example to get better understanding.

20 of 34

Promises

Three states of promises:

  • Pending - initial state
  • Fulfilled - operation completed successfully
  • Rejected - operation failed

21 of 34

Promise - static methods

Most common static methods:

  • Promise.all(iterable) - receives an array of promises and resolve when all promises are resolved of any is rejected
  • Promise.allSettled(iterable) - same as .all(), but wait until all promises are settled (resolved or rejected)
  • Promise.race(iterable) - receives an array of promises and waits until first promise is resolved or rejected

Use promises whenever you are using as async code.

Find more about Promises here.

22 of 34

4

ES6+ examples

23 of 34

ES6+

During this last presentation some of the most common ES6 features were shown, such as:

  • let, const, keyed collections

In this presentation we’ve explained Promises and Class syntax that is also part of ES6+.

You can find out what else was introduced in ES6 here.

On the next slides few important ES6+ features will be explained.

24 of 34

ES6+ (Arrow functions)

An arrow function expression has a shorter syntax compared to function expressions and does not have its own this, arguments, super, or new.target.

Two factors influenced the introduction of arrow functions:

  • Shorter functions
  • Non-binding of this

Read more about arrow functions

Try out this example

25 of 34

ES6+ (Destructuring)

Destructuring allows as to extract data from arrays or objects into distinct variables in an easy way.

// Array destructuring

const fruits = [‘apple’, ‘orange’, ‘banana’];

let [ fruit1, fruit2, fruit3 ] = fruits;

// Object destructuring

const person = {

name: ‘John’,

age: 35

};

let { name, age } = person;

26 of 34

ES6+ (Spread operator)

Spread operator allows us to explode an array into its individual items.

Let’s say we want to push items from one array to another, se example on the right.

// Array destructuring

let fruits = [‘apple’, ‘orange’, ‘banana’];

let moreFruits = [‘mango’, ‘kiwi’];

// If we just push moreFruits to fruits�// then we’ll push whole array into first array.�// We don’t want this.�first.push(moreFruits);

console.log(first); �// [‘apple’, ‘orange’, ‘banana’, [‘mango’, ‘kiwi’]]

// Instead we just want to push array items inside

first.push(...moreFruits);

console.log(first); �// [‘apple’, ‘orange’, ‘banana’, ‘mango’, ‘kiwi’]

27 of 34

ES6+ (Template literals)

Template literals are enclosed by backtick `` character which allows us to contain placeholders ${} and write strings in multiple rows.

let a = 5;

let b = 2;

console.log(`The sum is ${a + b}`); �

28 of 34

ES6+ (Modules)

Coding Javascript is all about managing our scope and our variables. How you organize the code is going to have a big impact on how well you can maintain your code.

  • Modules simplify our job at organizing our code.
  • Modules are pockets of functionality and each module has its own scope. A module often needs to import objects from other modules. They can also chose which objects get accessed by other modules.
  • When building modules we have to make a choice as to how we make them. This may depend on the functionality of the module, or how you go about designing your module in the first place.

29 of 34

ES6+ (Modules - Exports)

To access objects in a module, a module has to mark them for export. There are two kinds of exports:

  • Named exports (several per module): A module can export multiple objects by prefixing their declaration with “export” keyword.
  • Default exports (one per module): A module can pick which object to export by default by prefixing it with ”export default”. We can prefix any function, class or generator function with the keywords ”export default” to make a default export. This technique is especially useful when associating one class per module.

30 of 34

ES6+ (Modules - Imports)

Imports are used to import objects from another module. Whoever is using the module should understand how the module was built. Some modules export multiple objects, which we have to import via the named import. For the modules that export single/default object, we need to use default import:

  • Named imports: Syntax used for importing named imports can be for example like this: import { data1, data2 } from './data/data.js';
  • Default imports: Syntax used for importing default imports can be for example like this: import Cooking from './modules/cooking.js';

31 of 34

5

Hands-on

32 of 34

Hands-on

33 of 34

6

Homework

34 of 34

Homework