console.log('Hello world');
let name = 'Martin';
name = 'Lucas';
const surname = 'Nuc';
// 1) double quotes
let name = "Martin";
// 2) single quotes
let name = 'Martin';
// 3) backticks
let name = `Martin`;
let fullName = `${name} Nuc`;
let name = 'Martin';
console.log(name.toUpperCase());
let characters = name.split('');
console.log(characters); // ['M', 'a', 'r'...]
later...
let a = 5;
if (a === 5) {
console.log('is five');
}
for (let i = 0; i < 10; i++) {
// ...
}
let i = 0;
while(i < 10) {
// ...
i++;
}
if (isLoggedIn && (isWriter || isAdmin)) { ... }
if (user && product) { ... }
// defaults from any falsy value
let pageSize = userPageSize || 10;
let favoriteCoffee = usersFavorite || 'No favorite coffee';
// defaults only from null/undefined (allows '')
let favoriteCoffee = usersFavorite ?? 'No favorite coffee';
function add(a, b) {
return a + b;
}
const result = add(3,5);
// 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
// with body
const one = () => {
return 1;
};
// single returned statement
const two = () => 2;
function hello() {
function say(text) {
console.log(text)
}
say('hello');
}
function hello() {
say('hello');
function say(text) {
console.log(text)
}
}
"function hoisting"
function writeData(data, onComplete) {
fs.writeFileSync('file.txt', data);
onComplete();
}
writeData('hello', () => console.log('done'));
passing a function as parameter
function initialize() {
let cnt = 1;
return () => cnt++;
}
const fn = initialize();
console.log(fn()) // 1
console.log(fn()) // 2
console.log(fn()) // 3
let teacher = {
firstName: 'Martin',
surname: 'Nuc',
age: 32
}
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;
let teacher = {
firstName: 'Martin',
surname: 'Nuc',
age: 32
}
delete teacher.age;
console.log(teacher);
let firstName = 'Martin';
let age = 32;
// create object
let teacher = {
firstName: firstName,
age: age
}
// shorthand:
let teacher = {
firstName,
age
}
const martin = {
firstName: 'Martin',
age: 36
}
const richMartin = {
...martin,
money: 1000000
}
let teacher = {
firstName: 'Martin',
age: 32
}
let teacherTwo = teacher;
teacherTwo.age = 55;
console.log(teacher.age); // ????
const person = {
name: "John",
age: 25,
city: "New York"
};
// Task 1: Create updatedPerson by copying person and changing age to 30
// Task 2: Create personWithJob by adding a job property with the value "Engineer"
// Task 3: Create finalPerson by combining both updates in one step
const obj = {
one: function() { return 1; },
two: () => 2,
three() {
return 3;
}
};
obj.four = () => 4;
obj.one();
obj.two();
obj.three();
obj.four();
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
});
const obj = {
name: 'Martin',
surname: 'Nuc',
age: 32
};
const { name, surname, ...other } = obj;
console.log(other); // { age: 32 }
typeof 5 // 'number'
typeof 'hi' // 'string'
typeof {} // 'object'
typeof [] // 'object'
typeof undefined // 'undefined'
typeof null // 'object' !!
let items = [1, 2, 3]; // creation
items.push(4);
console.log(items); // [1, 2, 3, 4]
console.log(items.length) // 4
let arr = ['one', 'two', 'three'];
console.log(arr[0]); // 'one'
console.log(arr[1]); // 'two'
console.log(arr[5]); // undefined
const arr = ['one', 'two', 'three'];
const newArray = [...arr, 'four'];
let arr = [1, 2, 3, 4];
let output = arr.join('-');
console.log(output); // '1-2-3-4'
let arr = [1, 2, 3, 4];
arr.reverse();
console.log(arr); // [4, 3, 2, 1]
[1, 2, 3, 4].forEach(item =>
console.log(item)
);
let result = [1, 2, 3, 4].every(item =>
item > 0
);
console.log(result); // true
let result = [1, 2, 3, 4].map(item =>
item + 1;
);
console.log(result); // [2, 3, 4, 5]
let result = [1, 2, 3, 4].filter(x => x > 2);
console.log(result); // [3,4]
[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 |
'Good morning'.split(' '); // ['Good', 'morning']
let result = 'Good morning'
.replace('morning', 'afternoon');
let result = 'aaa,aab,aac,abc,acc'.match(/aa.?/g);
console.log(result) // [ 'aaa', 'aab', 'aac' ]
class Dog {
bark() {
console.log('woof-woof');
}
}
let rex = new Dog();
rex.bark();
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
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
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
console.log(1);
setTimeout(() => console.log(2), 1000);
setTimeout(() => console.log(3), 2000);
const timeoutRef = setTimeout(() => console.log(2), 1000);
clearTimeout(timeoutRef);
console.log(1);
setTimeout(() => console.log(2), 0);
console.log(3);
countdown(3)
3
2
1
Time's up!
this
class Dog {
constructor(name) {
this.name = name;
}
bark() {
console.log('woof-woof, I am ' + this.name);
}
}
let rex = new Dog('Rex');
rex.bark();
let obj = {
name: 'Martin',
sayHi() {
console.log(this.name);
}
}
obj.sayHi();
let fn = obj.sayHi;
fn();
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'
$('a').each(function() {
console.log(this.href);
});
let obj = {
name: 'Martin',
hi() {
console.log(this.name);
setTimeout(function () {
console.log(this.name);
}, 1000);
}
}
obj.hi();
let obj = {
name: 'Martin',
hi() {
console.log(this.name);
setTimeout(() => {
console.log(this.name);
}, 1000);
}
}
obj.hi();
obj = {a: 2, b: 3};
for(key in obj) {
console.log(key)
}
try {
throw new Error('Something went wrong')
} catch(e) {
console.error(e);
} finally {
console.log('this happens anyways')
}
throw 'Something went wrong'
throw new Error('Something went wrong')
setTimeout(() => {
console.log('after 1s');
setTimeout(() => {
console.log('after another 1s');
setTimeout(() => {
console.log('after another 1s');
}, 1000);
}, 1000);
}, 1000);
promise
.then(fn1)
.then(fn2)
.then(fn3)
pending
rejected
fullfilled
.then(...)
.catch(...)
= instantiate a Promise object
function wait5seconds() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(), 5000);
});
};
wait5seconds().then(() => console.log('after 5s'));
shorthand for resolved / rejected promise
Promise.resolve()
Promise.reject()
function wait5seconds() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve([1, 2, 3]), 5000);
});
};
wait5seconds().then((data) => console.log(data));
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.resolve('some data')
.then(data => 'hello' + data) // "hello" + "some data"
.then(data => console.log(data)) // "hello some data"
Promise.resolve('some data')
.then(data => 'hello' + data) // "hello" + "some data"
.then(data => console.log(data)) // "hello some data"
.then(data => fetch('https://google.com'))
.then(data => console.log(data)) // "<html><body>..."
Promise.all([...]).then(results => {
console.log(results[0]);
console.log(results[1]);
})
{
id: 1,
name: 'John Doe',
email: 'john.doe@example.com'
};
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 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'));
async function fn() {
const promise = new Promise(resolve => {
setTimeout(() => resolve('Hello'), 1000);
});
const data = await promise;
}
async function() {
try {
await Promise.reject('this is reason');
} catch (err) {
console.error(err);
}
}
async function() {
try {
await Promise.reject('this is reason');
} catch (err) {
console.error(err);
} finally {
console.log('done')
}
}
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
index.js
calculator.js
login.js
my-input.js
import { add, divide } from './calculator';
const result = add(5, divide(8, 2));
// calculator.js
export function add(a, b) { return a + b; }
export const divide = (a, b) => a / b;
export class Calculator { ... }
relative path
import PI from './calculator';
console.log(PI);
// calculator.js
export function add(a, b) { return a + b; }
export const divide = (a, b) => a / b;
export class Calculator { ... }
export default 3.14;
// default export can be called anyway
import mojePI from './calculator';
// named export
import { add as addNumbers } from './calculator'
addNumbers(2, 5);
Dependency management
{
"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": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
Shortcut for start and test scripts only. For others you have to use npm run
Runs any script from npm.
👉
npm install lodash
installs lodash library:
import lodash from 'lodash';
lodash.difference([1, 2, 3], [2, 3]);
{
"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
6.11.2
patch
minor version
major version
6.11.2
patch
minor version
major version
- major changes, breaks API
6.11.2
patch
minor version
- new features
- doesn't break API
major version
- major changes, breaks API
6.11.2
patch
- only bugfixes
minor version
- new features
- doesn't break API
major version
- major changes, breaks API
const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 25 },
{ name: 'David', age: 30 },
{ name: 'Edward', age: 35 }
];
{
25: 2,
30: 2,
35: 1
}
let obj = { name: "Martin" };
let weakRef = new WeakRef(obj);
let derefObj = weakRef.deref();
if (derefObj !== undefined) {
console.log(derefObj.name); // Output: "Martin"
} else {
console.log("The object has been garbage collected");
}
let weakMap = new WeakMap();
// Create some objects
let obj1 = { name: "Martin" };
let obj2 = { name: "John" };
// Set the objects as keys in the WeakMap
weakMap.set(obj1, "Developer");
weakMap.set(obj2, "Designer");
// Retrieve the values
console.log(weakMap.get(obj1)); // Output: "Developer"
console.log(weakMap.get(obj2)); // can be undefined