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++;
}
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) using arrow function (also anonymous)
const hello = () => console.log('hello');
named
anonymous
Arrow function
// with body
const one = () => {
return 1;
};
// single returned statement
const two = () => 2;
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
}
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
let obj = {
firstName: 'Martin',
surname: 'Nuc',
age: 32
};
let { name, surname } = obj;
console.log(name, surname);
function printAge({age}) {
console.log(age);
}
printAge({
name: 'Martin',
age: 32
});
typeof
typeof 5 // 'number'
typeof 'hi' // 'string'
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];
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
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);
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)
}
Let's get serious...
- create new folder (mkdir my-app; cd my-app)
- initialize node package:
-
npm init
-
- it creates package.json file which contains
- basic package info (author, licence, repository url, etc.)
- dependencies
- scripts
{
"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
What is npm?
Node package manager
- packaging system
- large repository 3rd party libs
- https://www.npmjs.com
npm install lodash
installs lodash library:
Use library in your code
const _ = require('lodash');
const words = _.words('Hello, how are you?');
// ['Hello', 'how', 'are', 'you']
console.log(words);
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
Use lodash
- install lodash library (https://lodash.com)
- use camelCase function from lodash to convert your full name to the camel case
Scripts
"scripts": {
"dev": "nodemon --exec npm run start",
"start": "node index.js",
"test": "mocha --opts mocha.opts"
},
- 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 your script
- create script called start for running your app
Global package
- available in your whole system
- sudo npm install -g benny-hill
- use them wisely
Read and write files
require('fs')
- https://nodejs.org/api/fs.html
- synchronous vs asynchronous functions
Write file
const fs = require('fs');
fs.writeFileSync('file.txt', 'Hello');
Read file
const fs = require('fs');
let content;
content = fs.readFileSync('file.txt', 'utf8');
Let's try it out !
- write "Hello world" into a file
- wait 3 seconds then read the file and print it out
Asynchronous functions
- eg. fs.writeFileSync(...) becomes fs.writeFile(..., callback)
- does not block
- callbacks
- 1st callback argument is usually error
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, content) => {
console.log('reading done', content);
});
Try it yourself :-)
- rewrite previous task in async manner
- create file with "Hello world"
- wait 3 seconds
- read it and print
setTimeout(callback, time)
- executes after <time> ms
- uses callback function
const timeoutReference = setTimeout(() => {
console.log('after 3s');
}, 3000);
cancelling timeout
clearTimeout(timeoutReference);
setInterval(callback, time)
- executes every <time> ms
const intervalReference = setInterval(() => {
console.log('every 3s');
}, 3000);
cancelling timeout
clearInterval(intervalReference);
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
Promise state
- pending
- fulfilled
- rejected
pending
rejected
fullfilled
.then(...)
.catch(...)
How to create a promise
- Promise.resolve()
- Promise.reject()
- instantiate a Promise object
function wait5seconds() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(), 5000);
});
};
wait5seconds().then(() => console.log('after 5s'));
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())
.then(() => {
return 'hello';
})
.then(param => console.log(param)); // hello
Waiting for multiple promises
- Promise.all([promise1, promise 2])
- returns a single promise
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'));
Catch in async functions
async function() {
try {
await Promise.reject('this is reason');
} catch (err) {
console.error(err);
}
}
Nanoenergies Javascript essentials
By Martin Nuc
Nanoenergies Javascript essentials
- 305