1 of 51

5 - Intro to JavaScript.

Speck Academy 2021

2 of 51

How it works

Javascript basics

Functions

Collections

Objects

Promises

ES6+

Overview

1

2

3

4

5

6

7

3 of 51

1

How it works

4 of 51

How it works overview

About JavaScript

ECMAScript

JS engine

Execution context

Hoisting

5 of 51

About JavaScript

JavaScript is a cross-platform, object-oriented language based on prototypes used to make webpages interactive.

  • Client-side JavaScript extends the core language by supplying objects to control a browser and its DOM. For example, client-side extensions allow an application to place elements on an HTML form and respond to user events such as mouse clicks, form input, and page navigation
  • Server-side JavaScript extends the core language by supplying objects relevant to running JavaScript on a server. For example, server-side extensions allow an application to communicate with a database, manipulate with files on a server

6 of 51

About JavaScript

JavaScript can change the way the webpage (DOM) looks. And, likewise, Node.js JavaScript on the server can respond to custom requests from code written in the browser.

Similar to Java, but in some ways different:

  • Dynamically typed (types can change in runtime)
  • Loosely typed (don’t have to explicitly specify types of variables and objects )
  • Prototype-based object model
  • Functions can be properties of objects
  • Properties can be added to any object dynamically
  • Single-threaded language (code is executed line by line in the main thread)

7 of 51

ECMAScript

ECMA - European Computer Manufacturers Association

Scripting language that forms the basis of JavaScript.

Standardized version of JavaScript - behaves the same way in all applications that support the standard.

  • Set of requirements for implementing standards-compliant language features in your ECMAScript implementation or engine (V8, SpiderMonkey)
  • JavaScript supports all functionality outlined in the ECMAScript specification
  • Current standard is ECMA-262 approved by ISO-16262
  • JavaScript version history (Mozilla/SpiderMonkey)

8 of 51

JS engine

JS engine is a program, found in a hosting environment such as browser, that executes JS code. It consists of two main parts:

  • Memory Heap - a large and unstructured area of memory, objects (function, arrays) are allocated here. No defined limit (except for the hardware limitations of the computer), relatively slow access.
  • Call Stack - an abstract data structure located in a special region of the computer’s memory, and managed by the CPU. The stack uses LIFO (Last In First Out) principle to temporarily store and manage function invocation calls. Stack grows and shrinks as functions push on and pop off it. It has defined limit (maximum call stack in hosting environment), fast access.

9 of 51

JS engine

Popular JS engines:

  • V8 (Chrome, Node.js)
  • SpiderMonkey (Firefox)
  • JavaScriptCore (Safari)
  • Chakra (IE, Edge)

In order to improve performance, V8 translates the JS code directly into machine code during execution (JIT compiler).

V8 engine uses several threads for each process internally:

  • Main thread, compiling thread, a profiler thread, garbage collector threads

10 of 51

JS engine

Process

  • Program in execution
  • Can contain multiple threads
  • Has independent address space

Thread

  • Independent path of process execution
  • Shares address space with other threads from the same process
  • Multiple threads from the same process share state, memory…
  • Each thread has its own call stack, id, priority level...

11 of 51

Execution context

Execution context is a wrapper in which the function is executed and which stores all of the relevant data of a function (variables, parameters, scope chain, value of this etc.).

The default execution context in JS is the Global Execution Context (GEC):

  • Code that is not inside any function
  • Associated with the global object (browser: window; node.js: global)

Each function gets a new execution context (internally implemented object) with a reference to it stored on top of the call stack.

12 of 51

Execution context

Call (execution) stack

global execution context

a = 0

‘#909dda’

pointer

13 of 51

Execution context

Call (execution) stack

global execution context

a = 0

first(a)

b = 1

‘#123aba’

pointer

14 of 51

Execution context

Call (execution) stack

global execution context

a = 0

first(a)

b = 1

second(b)

c = 2

‘#423fef’

pointer

15 of 51

Execution context

Call (execution) stack

global execution context

a = 0

first(a)

b = 1

second(b)

c = 2

third(c)

d = 3

‘#333eef’

pointer

16 of 51

Execution context

1. Creation phase (during compilation)

  • VO is created, contains all the function arguments and inner function declarations
  • The scope chain is created - a list of all the VO’s inside which the current function exists
  • Value of “this” is initialized

2. Execution phase

  • JS engine scans through the function again and update the VO with the values of the variables
  • Code is executed

EXECUTION CONTEXT OBJECT

Variable object (VO)

Scope chain

“this” variable

17 of 51

Execution context - creation phase

Execution context object for thrones is created and reference to it is pushed to the Call stack.

Execution context object - creation phase

18 of 51

Execution context - execution phase

At execution phase values will be assigned to all of the declared variables in that execution context.

Execution context object - execution phase

19 of 51

Execution context

Variable object (VO) is a special object which stores variables, function declarations and parameters.

  • For each function declaration, a property is created pointing to that function
  • For each variable, a property is created and set to undefined

EXECUTION CONTEXT OBJECT

Variable object (VO)

Scope chain

“this” variable

20 of 51

Execution context

Scope is created inside functions (with ES6 scope also can be created inside if, for, do/while blocks).

  • Scope is the space in which the defined variables are accessible
  • Function that is lexically (written inside) within another function gets access to the scope of the outer function
  • The inner function gets access to the variables and functions of the outer functions
  • Scope chain is a list of all the VO’s inside which the current function exists (current, outer, global VO’s)
  • More info

EXECUTION CONTEXT OBJECT

Variable object (VO)

Scope chain

“this” variable

21 of 51

Execution context

Scope chain

Global scope

[VOglobal]

one() scope

[VOone] + [VOglobal]

two() scope

[VOtwo] + [VOone] + [VOglobal]

scope chain

22 of 51

Execution context

“this” variable - The last step in the creation of the execution context object is the assignment of value to the “this” property.

  • The value of “this” has nothing to do where function is declared lexically (where it was written), but how it was called

EXECUTION CONTEXT OBJECT

Variable object (VO)

Scope chain

“this” variable

23 of 51

Execution context

Rules for “this” keyword

  • Default binding - if the function is called from the GEC, then “this” is bound to the window object
  • Implicit binding - if the function is owned by an object and called as a method call of the object, then “this” is bound to that object
  • Explicit binding - if the function is called with call, apply or bind, then the value of “this” is explicitly bound to the specified object
  • For better understanding, open up this example!

EXECUTION CONTEXT OBJECT

Variable object (VO)

Scope chain

“this” variable

24 of 51

Execution context

“this” keyword in ES6 arrow functions

  • In ES6 “this” doesn’t depend on the call-site because arrow function captures the “this” value of the outer function.

EXECUTION CONTEXT OBJECT

Variable object (VO)

Scope chain

“this” variable

25 of 51

Hoisting

Variable hoisting - var

  • You can refer to variable declared later, without getting exception
  • Variables in JS are hoisted (lifted) to the top of the function or statement.
  • Hoisted variables return a value of undefined

Variable hoisting - let and const

  • let and const are hoisted but not initialized
  • Referencing the variable in the block before the variable declaration results in a ReferenceError

26 of 51

Hoisting

Function hoisting

  • In case of functions, only function declarations are hoisted
  • Function expressions are not hoisted

This is great video that explains how JavaScript works!

27 of 51

2

JavaScript basics

28 of 51

Javascript basics overview

Grammar and types

Control flow and errors

Loops

29 of 51

Grammar and types

JS is a case-sensitive and uses Unicode character set.

Comments:

  • // one line comment
  • /* Multiline comment */

Variable declarations:

  • Identifier of variable must start with a letter, underscore or dollar sign
  • Local and global variables depending on the execution context - var
  • Block-scoped variables - let, const

30 of 51

Grammar and types

Latest ECMAScript standard defines eight data types:

  • Boolean - true and false
  • null - special keyword denoting a null value
  • undefined - a top-level property whose value is not defined
  • Number - an integer or floating point
  • BigInt - an integer with arbitrary precision
  • String - a sequence of characters
  • Symbol - a data types whose instances are unique and immutable
  • Object - only type that is not primitive

Read more here

31 of 51

Control flow

Block statements are commonly used with control flow statements (if, for, while)

Conditional statements:

  • if...else - use the if statement to execute a statement if a logical condition is true. Use the optional else clause to execute a statement if the condition is false.
  • switch - allows program to evaluate an expression and attempt to match the expression’s value to a case label. If a match is found, the program executes the associated statement

32 of 51

Errors

You can throw exceptions using the throw statement and handle them using the try...catch statements.

try...catch statement:

  • Marks a block of statements to try
  • If exception is thrown, the catch block catches it
  • In other words, you want to try block to succeed - but if it doesn’t, you want to pass to the catch block
  • finally block also can be part of the try...catch statement, if exists it is always executed (useful to close files, DB connection etc.)

Find out more about control flow and error handling.

33 of 51

Loops

Loops offer a quick and easy way to do something repeatedly.

Statements for loops (find more here):

  • for
  • do...while
  • while
  • labeled statement
  • break statement
  • continue
  • for...in
  • for...of

34 of 51

3

Functions

35 of 51

Functions

Defining functions

Closures

Callback functions

Arrow functions

36 of 51

Defining functions

A function is a JavaScript procedure - a set of statements that performs a task or calculates a value.

A function definition (function declaration, function statement) consists of the function keyword, followed by:

  • The name of the function
  • A list of parameters to the function (ES6 allows default values of parameters)
  • The JavaScript statements that define the function

// Function declaration

function getFullName(first, last = ‘Moe’){� var fullName = first + ‘ ’ + last;

return fullName;

}

// Function call

getFullName(‘John’, ‘Doe’);

// Console

> John Doe

37 of 51

Defining functions

Functions can also be created like a function expression.

Function expression can be named function (for recursive purpose) or anonymous which means it doesn’t have to have a name.

Function expression can’t be hoisted, so if you call function before it’s definition, error will be thrown.

// Function expression

var getFullName = function(first, last){� return first + ‘ ’ + last;

}

// Function call

getFullName(‘John’, ‘Doe’);

// Console

> John Doe

38 of 51

Closures

A closure is an expression (most commonly function) that can have free variables together with an environment that binds those variables (that “closes” the expression).

Nested Function is a closure, this means that a nested function can “inherit” the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.

  • Inner function can be accessed only from statements in the outer function
  • The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function

39 of 51

Closures

Closures provide us a sort of encapsulation for the variables of the inner function.

Nested Function is a closure, this means that a nested function can “inherit” the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.

// Closure

function outside(x){

var outLength = x;

function inside(y){

var innLength = y;� return outLength - innLength;

}

return inside;

}

// Function call

outside(100)(70);

// Console

> 30

40 of 51

Callback functions

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

Callback function is often used to continue code execution after asynchronous operation has completed.

Example on the right simulates a request to server. Try out here!

// Function that simulates a server request

function serverRequest(query, callback){

setTimeout(function(){

var response = query + ‘full!’;� callback(response);

}, 5000);

}

// Function which will be passed as an callback

function getResults(results){

console.log(‘Server response: ’ + results);

}

// Function call

serverRequest(‘The glass is half ’, getResults);

// Console response after 5 seconds

> Server response: The glass is half full!

41 of 51

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

// Same thing can be written in two ways�// Function expression

const f1 = function(x){ return x; }

// Arrow function expression

const f2 = x => x;

42 of 51

4

Collections

43 of 51

Collections overview

Indexed collections - Arrays

Keyed collections

44 of 51

Indexed collections - Arrays

Arrays are collections of data which are ordered by an index value.

JavaScript doesn’t have an explicit array data type. However, you can use the predefined Array object and its methods to work with arrays in your applications.

Try to become familiar with an array methods, some of the most common methods are listed on the next slide.

All of the important things about arrays can be found here.

45 of 51

Indexed collections - Arrays

Array methods are often used in development, and some the most common are:

  • concat - joins two arrays and returns a new array
  • push - adds one or more elements to the end of an array and returns the length
  • pop - removes the last element from an array and returns that element
  • shift - removes the first element from an array and returns that element
  • unshift - adds one or more elements to the front of an array and returns the new length
  • slice - extracts a section of an array and returns a new array
  • splice - removes elements from an array and (optionally) replaces the items which were removed from the array
  • reverse - transposes the elements of an array (first element becomes the last and the last becomes the first), it returns reference to the array

46 of 51

Keyed collections

Collections of data which are ordered by a key.

  • Map
  • Set

ECMAScript 2015 introduces a new data structure to map values to values.

Main difference between Map and Set:

  • A value in Set may only occur once, it’s unique in the Set’s collection
  • Map allows us to store duplicate values in the collection

Read more about keyed collections

47 of 51

Keyed collections

Object and Map compared:

  • The keys of an Object are Strings or Symbols, where they can be of any value for a Map
  • You can get the size of a Map easily, while you have to manually keep track of size for Object
  • The iteration of maps is in insertion order of the elements

Use maps over objects:

  • when keys are unknown until run time, and when all keys are the same type and all values are the same type.
  • If there is need to store primitive values as keys because object treats each key as a string

48 of 51

5

Hands-on

49 of 51

Hands-on

50 of 51

6

Homework

51 of 51

Homework

Link to Homework