Javascript

essentials

History of Javascript

  • 1995 - Javascript in Netscape browser
  • 2005 - AJAX based applications (Gmail)
  • 2008 - Google Chrome with V8 engine
  • 2009 - nodejs

What is node.js?

  • environment for running Javascript
  • doesn't need browser
  • using V8

Install node

 ➡️ Hello world

  • create file index.js with Javascript code
  • execute file using: node index.js
console.log('Hello world');

Javascript

Variables

  • var
  • let, const
let name = 'Martin';
name = 'Lucas';
const surname = 'Nuc';

Basic types

  • number
  • string
  • boolean
  • null, undefined
  • objects

Strings

// 1) double quotes
let name = "Martin";

// 2) single quotes
let name = 'Martin';

// 3) backticks
let name = `Martin`;

let fullName = `${name} Nuc`;

Strings

let name = 'Martin';
console.log(name.toUpperCase());

let characters = name.split('');
console.log(characters); // ['M', 'a', 'r'...]
  • have methods

null, undefined

  • undefined = value was not set
  • null = "nothing"
    • value set but it means "nothing" on purpose

Objects

later...

Loops

  • for
  • while

Conditions

let a = 5;
if (a === 5) {
    console.log('is five');
}
for (let i = 0; i < 10; i++) {
    // ...
}

let i = 0;
while(i < 10) {
    // ...
    i++;
}

Use === for comparison

Functions

  • sequence of commands
  • inputs
  • output
    • no return = undefined
function add(a, b) {
    return a + b;
}

How to create a function?

// 1) named function
function hello() {
    console.log('hello');
}

// 2) anonymous function
const hello = function() {
    console.log('hello');
}

// 3) anonymous using arrow function
const hello = () => console.log('hello');

named

anonymous

Arrow function

// with body
const one = () => {
    return 1;
};

// single returned statement
const two = () => 2;

Clojure

function initialize() {
  let cnt = 1;
  return () => cnt++;
}

const fn = initialize();
console.log(fn()) // 1
console.log(fn()) // 2
console.log(fn()) // 3
  • function see surrounding variables
    = lexical context

Objects

Objects

  • not a primitive type
  • used for structured data
  • key: value
  • key = property
let teacher = {
    firstName: 'Martin',
    surname: 'Nuc',
    age: 32
}

Modify object

let teacher = {
    firstName: 'Martin',
    surname: 'Nuc',
    age: 32
}

// using dot notation
teacher.age = 33;

// using key name
teacher['age'] = 33;

let keyName = 'age';
teacher[keyName] = 33;

Remove property

let teacher = {
    firstName: 'Martin',
    surname: 'Nuc',
    age: 32
}

delete teacher.age;
console.log(teacher);

Shorthand when creating object

let firstName = 'Martin';
let age = 32;

// create object
let teacher = {
    firstName: firstName,
    age: age
}

// shorthand:
let teacher = {
    firstName,
    age
}

Spread operator

const martin = {
  firstName: 'Martin',
  age: 36
}

const richMartin = {
  ...martin,
  money: 1000000
} 
  • used to create a new object from another object

Stored as a reference

let teacher = {
    firstName: 'Martin',
    age: 32
}
let teacherTwo = teacher;

teacherTwo.age = 55;
console.log(teacher.age); // ????
  • not like primitive types
  • use Object.assign() to create a copy (not in IE11)

Methods in objects

const obj = {
    one: function() { return 1; },
    two: () => 2,
    three() {
        return 3;
    }
};
obj.four = () => 4;

obj.one();
obj.two();
obj.three();
obj.four();

Destructuring object

const obj = {
    firstName: 'Martin',
    surname: 'Nuc',
    age: 32
};

const { firstName, surname } = obj;
console.log(name, surname);

function printAge({age}) {
    console.log(age);
}

printAge({
    name: 'Martin',
    age: 32
});

Rest operator

const obj = {
    name: 'Martin',
    surname: 'Nuc',
    age: 32
};

const { name, surname, ...other } = obj;
console.log(other); // { age: 32 }

  • "rest" after destructuring

typeof

typeof 5 // 'number'
typeof 'hi' // 'string'
typeof {} // 'object'
typeof [] // 'object'
typeof undefined // 'undefined'

typeof null // 'object' !!

Arrays

Arrays

  • store multiple items
  • in order
  • .length = number of items
  • push to add
let items = [1, 2, 3]; // creation
items.push(4);

console.log(items); // [1, 2, 3, 4]
console.log(items.length) // 4

Access the index

  • index starts with 0
let arr = ['one', 'two', 'three'];

console.log(arr[0]); // 'one'
console.log(arr[1]); // 'two'

console.log(arr[5]); // undefined

Spread operator

  • expands array into individual items
  • used to create a new array from existing
const arr = ['one', 'two', 'three'];

const newArray = [...arr, 'four'];

➡️ Palindrome

  • create a function which determines whether input is palindrome
    • palindrome = word that reads the same backwards as forwards

Array methods

.join()

let arr = [1, 2, 3, 4];
let output = arr.join('-'); 
console.log(output); // '1-2-3-4'
  • creates string by joining items in the array

.reverse()

let arr = [1, 2, 3, 4];
arr.reverse();
console.log(arr); // [4, 3, 2, 1]

.forEach()

  • loops over the array
[1, 2, 3, 4].forEach(item =>
    console.log(item)
);

.every(), .some()

  • checks condition for every item
let result = [1, 2, 3, 4].every(item =>
    item > 0
);
console.log(result); // true

.map()

  • creates a new array
  • every item modified by a function
let result = [1, 2, 3, 4].map(item =>
    item + 1;
);
console.log(result); // [2, 3, 4, 5]

.filter()

  • creates a new array
  • includes only items that pass the condition
let result = [1, 2, 3, 4].filter(x => x > 2);
console.log(result); // [3,4]

.reduce()

  • accumulates intermediate result
[1,2,3,4].reduce((accumulator, current) =>
    accumulator + current
, 0); // 10
accumulator current result
0 1 1
1 2 3
3 3 6
6 4 10

➡️ Sum of positives

  • you have an array of numbers
  • (1) count how many positive numbers are there
    • example: [1,-4,7,12] => 3
  • (2) you would like to calculate sum of positive values only
    • example: [1,-4,7,12] => 1 + 7 + 12 = 20

String methods

.split()

  • creates an array
  • split by character
'Good morning'.split(' '); // ['Good', 'morning']

.replace()

  • replaces only first match and returns a new string
let result = 'Good morning'
    .replace('morning', 'afternoon');

.match()

  • search using RegEx
let result = 'aaa,aab,aac,abc,acc'.match(/aa.?/g);
console.log(result) // [ 'aaa', 'aab', 'aac' ] 

➡️ Shortest word

  • given a string of words, return the length of the shortest word(s)
  • example: "Hi my name is Martin" => 2

Classes

What is a class?

  • template for future objects
  • needs to be instantiated using new keyword
  • like a "recipe" for a chocolate cake. Using recipe you make a cake (instance of a cake)
class Dog {
    bark() {
        console.log('woof-woof');
    }
}
let rex = new Dog();
rex.bark();

Might have properties

class Dog {
    setName(newName) {
        this.name = newName;
    }
    bark() {
        console.log('woof-woof, I am ' + this.name);
    }
}

let rex = new Dog();
rex.setName('Rex');
let lassie = new Dog();
lassie.setName('Lassie');

rex.bark();  // woof-woof, I am Rex
lassie.bark();  // woof-woof, I am Lassie
  • use this keyword to access properties

Constructor

class Dog {
    constructor(name) {
        this.name = name;
    }
    bark() {
        console.log('woof-woof, I am ' + this.name);
    }
}

let rex = new Dog('Rex');
rex.bark();  // woof-woof, I am Rex
  • method which is executed when the class is instantiated (when used with new)

Inheritance

class Animal {
    eat() {
        console.log('yum yum');
    }
}

class Dog extends Animal {
    constructor(name) {
        this.name = name;
    }
    bark() {
        console.log('woof-woof, I am ' + this.name);
    }
}

let rex = new Dog('Rex');
rex.bark();  // woof-woof, I am Rex
rex.eat(); // yum yum
  • class can extend another class
  • parent class should be more generic

setTimeout

setTimeout()

  • do something later
  • asynchronous
console.log(1);
setTimeout(() => console.log(2), 1000);
setTimeout(() => console.log(3), 2000);

Event loop

  • JS is single-threaded
  • things get pull from event loop
console.log(1);
setTimeout(() => console.log(2), 0);
console.log(3);

Context

this

What is context?

  • the value of this keyword
  • related not only to classes, it's everywhere
  • typically it's set to object which the function belongs to BUT you never know
class Dog {
    constructor(name) {
        this.name = name;
    }
    bark() {
        console.log('woof-woof, I am ' + this.name);
    }
}

let rex = new Dog('Rex');
rex.bark();

Context

  • depends on how the function is called
let obj = {
    name: 'Martin',
    sayHi() {
        console.log(this.name);
    }
}

obj.sayHi();
let fn = obj.sayHi;
fn();

Enforce context

  • using call+apply, bind
function fn(num) {
    console.log(this, num);
}

// classic invocation
fn(1); // this = undefined

// call + apply
fn.call('test', 2); // this = 'test'
fn.apply('test', [3]); // this = 'test'

// bind
let bound = fn.bind('test');
bound(4); // this = 'test'

Example

  • jQuery uses context:
$('a').each(function() {
  console.log(this.href);
});

Problem

  • What context does a callback function have?
let obj = {
  name: 'Martin',
  hi() {
    console.log(this.name);
    setTimeout(function () {
      console.log(this.name);
    }, 1000);
  }
}

obj.hi();

Arrow functions

  • always pass the current context
let obj = {
  name: 'Martin',
  hi() {
    console.log(this.name);
    setTimeout(() => {
      console.log(this.name);
    }, 1000);
  }
}

obj.hi();

 ➡️ Test your JS skills

  • Write a function to find the first not repeated (unique) character in a string
obj = {a: 2, b: 3};
for(key in obj) {
  console.log(key)
}

Promises

What are they for

  • to avoid "callback hell"
  • flat and readable code
  • mostly used for asynchronous operations
    • any asynchronous operation can be wrapped to a Promise

Problem: callback hell

setTimeout(() => {
  console.log('after 1s');
  setTimeout(() => {
    console.log('after another 1s');
    setTimeout(() => {
      console.log('after another 1s');
    }, 1000);
  }, 1000);
}, 1000);

Flat code with Promises

promise
  .then(fn1)
  .then(fn2)
  .then(fn3)

Promise state

  • pending
  • fulfilled (=resolved)
  • rejected

pending

rejected

fullfilled

.then(...)

.catch(...)

How to create a promise

= instantiate a Promise object

function wait5seconds() {
    return new Promise((resolve, reject) => {
        setTimeout(() => resolve(), 5000);
    });
};

wait5seconds().then(() => console.log('after 5s'));

How to create a promise

shorthand for resolved / rejected promise

Promise.resolve()
Promise.reject()

Pass data

  • argument of resolve
  • obtained in the first parameter of then
function wait5seconds() {
    return new Promise((resolve, reject) => {
        setTimeout(() => resolve([1, 2, 3]), 5000);
    });
};

wait5seconds().then((data) => console.log(data));

1. Error handling - catch

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => reject('This is error'), 5000);
    });
};

fetchData()
  .then((data) => console.log('success', data))
  .catch((error) => console.log(error));

Promise chaining

  • what you return in then you get in the next then
  • when it returns a Promise it will wait for that promise to resolve before going to next then
Promise.resolve('hey')
    .then(data => console.log(data)) // "hey"
    .then(() => anotherPromise()) // async
    .then(() => {
        return 'hello'; // sync
    })
    .then(param => console.log(param)); // "hello"

Waiting for multiple promises

  • Promise.all([promise1, promise 2])
    • returns a single promise - resolved when all of them are resolved
  • Promise.race([promise1, promise 2])
    • resolved when the fastest one is resolved 

➡️ Wrap setTimeout in Promise

  • create function wait
    • parameter: how long it should wait
  • use promise chain (.then) to count down:
    • console.log: 3,2,1, go!

async / await

async/await

  • syntactic sugar around promises
  • works only in async function
async function countDown() {
    console.log(3);
    await wait(1000);
    console.log(2);
    await wait(1000);
    console.log(1);
    await wait(1000);
    console.log('go!');
}

countDown().then(() => console.log('done'));

async/await

async function countDown() {
    console.log(3);
    await wait(1000);
    console.log(2);
    await wait(1000);
    console.log(1);
    await wait(1000);
    console.log('go!');
}

countDown().then(() =>
   console.log('done'));
function countDown() {
    console.log(3);
    return wait(1000)
      .then(() => console.log(2))
      .then(() => wait(1000))
      .then(() => console.log(1)
      .then(() => wait(1000))
      .then(() => console.log('go!'))
}

countDown().then(() =>
   console.log('done'));

Extract resolved data

async function fn() {
  const data = await Promise.resolve('hello');
}

Error handling in async fn

async function() {
    try {
        await Promise.reject('this is reason');
    } catch (err) {
        console.error(err);
    }
}

➡️ Rewrite using async/await

function fetchData(url) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      Math.random() < 0.5 ? resolve(Math.random()) : reject('Fetching failed')
    }, 1000);
  })
}

function execute() {
  const results = [];
  fetchData('seznam.cz')
    .then((seznamData) => results.push(seznamData))
    .then(() => fetchData('google.com'))
    .then((googleData) => results.push(googleData))
    .catch(error => console.log(error))
    .then(() => console.log('done'))
}

fetchData ramdomly fails

NPM

 

Dependency management

Node package manager

{
  "name": "my-package",
  "version": "1.0.0",
  "description": "This is just description of my awesome package",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon --exec npm run start",
    "start": "tsc && node dist/index.js",
    "test": "mocha --opts mocha.opts"
  },
  "author": "Martin Nuc",
  "license": "ISC",
  "dependencies": {
    "@types/chai": "4.0.4",
    "@types/mocha": "2.2.43",
    "@types/node": "8.0.28",
    "@types/sinon": "2.3.4",
    "chai": "4.1.2",
    "mocha": "3.5.3",
    "nodemon": "1.12.1",
    "sinon": "3.2.1",
    "ts-node": "3.3.0",
    "typescript": "2.5.2"
  }
}

package.json

Scripts


"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject"
},
  • used to execute commands
  • npm dependencies executables resolution (from node_modules/.bin/*)

npm run <name>

Shortcut for start and test scripts only. For others you have to use npm run

Runs any script from npm.

npm start

npm test

👉

➡️ Create NPM project

  • create a folder and run npm init
  • create index.js
  • create start script to run it

Dependencies

npm install lodash

installs lodash library:

Use library in your code

import lodash from 'lodash';
lodash.difference([1, 2, 3], [2, 3]);

Dependencies and GIT

  • we don't commit dependencies
  • put node_modules folder in .gitignore
  • npm install to install dependencies
{
  "name": "my-package",
  "version": "1.0.0",
  "description": "This is just description of my awesome package",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon --exec npm run start",
    "start": "tsc && node dist/index.js",
    "test": "mocha --opts mocha.opts"
  },
  "author": "Martin Nuc",
  "license": "ISC",
  "dependencies": {
    "@types/chai": "4.0.4",
    "@types/mocha": "2.2.43",
    "@types/node": "8.0.28",
    "@types/sinon": "2.3.4",
    "lodash": "4.17.5",
    "chai": "4.1.2",
    "mocha": "3.5.3",
    "nodemon": "1.12.1",
    "sinon": "3.2.1",
    "ts-node": "3.3.0",
    "typescript": "2.5.2"
  }
}

package.json

Semantic versioning

6.11.2

patch

minor version

major version

Semantic versioning

6.11.2

patch

minor version

major version

- major changes, breaks API

Semantic versioning

6.11.2

patch

minor version

- new features

- doesn't break API

major version

- major changes, breaks API

Semantic versioning

6.11.2

patch

- only bugfixes

minor version

- new features

- doesn't break API

major version

- major changes, breaks API

Tieto Javascript essentials

By Martin Nuc

Tieto Javascript essentials

  • 197