Created
August 6, 2017 13:25
-
-
Save OlehRovenskyi/b84c58fbbc7d3456041377670d8d96a5 to your computer and use it in GitHub Desktop.
JavaScript2015
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ---- let const ---- | |
const a = 5; | |
let b = 10; | |
if (true) { | |
let a = 1; | |
let b = 2; | |
const c = 3; | |
console.log(a, b); // 1 2 | |
console.log(c); // 3 | |
} | |
console.log(a, b); // 5 10 | |
// console.log(c); // Error | |
// ------ | |
const consA = 1; | |
if (true) { | |
console.log(consA); | |
// consA = 2; | |
// console.log(consA); | |
} | |
const constObj = { | |
a: 1 | |
}; | |
console.log(constObj); | |
constObj.a = 2; | |
console.log(constObj); | |
// ---- let const ---- | |
// каждый цикл имеет свою переменную i | |
for(let i = 0; i<10; i++) { /* … */ } | |
for(let i = 0; i<10; i++) { /* … */ } | |
// console.log( i ); // ошибка: глобальной i нет | |
// ---- ES6 - Destructuring ---- | |
let obj = { | |
name: 'Ivan', | |
addresses: ['Addr 1', 'Addr 2'], | |
family: { | |
mother: { | |
name: 'Olha', | |
age: 60 | |
} | |
} | |
}; | |
let { | |
name, | |
addresses: where = 'Nowhere', | |
salary = 1000, | |
family: { | |
mother | |
} | |
} = obj; | |
console.log(name, where, salary, mother.name); | |
// Ivan [Addr 1, Addr 2] 1000 Olha | |
// ---- | |
let [firstName, lastName] = ["Илья", "Кантор"]; | |
console.log(firstName); // Илья | |
console.log(lastName); // Кантор | |
// ---- object | |
let fName = 'Arni'; | |
let lName = 'Vik'; | |
let userInfo = { | |
fName, | |
lName | |
}; | |
console.log(userInfo); | |
// ---- | |
let options = { | |
title: "Меню", | |
width: 100, | |
height: 200 | |
}; | |
let { title, width, height } = options; | |
console.log(title); // Меню | |
console.log(width); // 100 | |
console.log(height); // 200 | |
// ---- spread | |
'use strict'; | |
let [firstName1, lastName1, ...rest] = "Юлий Цезарь Император Рима".split(" "); | |
console.log(firstName1); // Юлий | |
console.log(lastName1); // Цезарь | |
console.log(rest); // Император,Рима (массив из 2х элементов) | |
// ---- ES6 - default value | |
'use strict'; | |
let [firstName2, lastName2] = []; | |
console.log(firstName2); // undefined | |
// --- | |
'use strict'; | |
// значения по умолчанию | |
let [firstName3="Гость", lastName3="Анонимный"] = []; | |
console.log(firstName3); // Гость | |
console.log(lastName3); // Анонимный | |
// ---- ES6 - Strings and RegEx ---- | |
let s = 'Test'; | |
if (s.startsWith('T')) { | |
console.log('Starts '.repeat(2)); | |
} else { | |
console.log('Does not Start '.repeat(2)); | |
// Does not Start Does not start | |
} | |
// ---- ES6 - Strings and Templating ---- | |
// много строчный текст | |
console.log(`моя | |
многострочная | |
строка`); | |
let i = 1; | |
let message = ` | |
Hello User-${i}. | |
Hello User-${++i}. | |
Hello User-${++i}! | |
`; | |
console.log(message); // Hello User1. Hello User-2. Hello User-3! | |
// ---- ES6 - Functions - Default values ---- | |
function getValue(value) { | |
return value + 5; | |
} | |
function add(first = 0, second = getValue(first)) { | |
return first + second; | |
} | |
console.log(add()); // 5 | |
console.log(add(1)); // 7 | |
console.log(add(1, 1)); // 2 | |
// ---- ES6 - Functions - Spread ---- | |
function check(...args) { | |
return args[0]; | |
} | |
console.log(check(null)); // | |
console.log(check(1)); // 1 | |
console.log(check(2, 4, 6)); // 2 | |
console.log(check([1, 1], [2, 2], [3, 3])); // 1,1 | |
let values= [1,2,3]; | |
console.log(Math.max(...values)); // 3 | |
console.log(Math.max(...values, 1)); // 3 | |
console.log(Math.max(...values, 4)); // 4 | |
// ---- Spread vs Arguments ---- | |
function check2(...spred) { | |
spred.forEach((item) => { | |
console.log(item) | |
}) | |
} | |
check2(1,2,3); | |
function check3(a,b,c) { | |
// arguments.forEach((item) => { | |
// console.log(item) | |
// }) | |
} | |
check3(1,2,3); | |
// ---- ES6 - arrow function | |
let doNothing = () => {}; | |
let sum = (num1, num2) => num1 + num2; | |
console.log(sum(1, 2)); // 3 | |
let values2 = [5, 10, 0, 20]; | |
console.log(values2.sort((a, b) => a - b)); // 0,5,10,20 | |
// ---- ES6 - Objects ---- | |
function CreatePerson(name, age) { | |
return { name, age, hello() { return `Hello ${this.name}`;} }; | |
} | |
let person = new CreatePerson('Ivan', 30); | |
console.log(person.hello()); // Hello Ivan | |
// Object.is insead of === | |
console.log(Object.is(5, 5)); // true | |
console.log(Object.is(5, "5")); // false | |
console.log( Object.is(+0, -0)); // false | |
console.log( +0 === -0 ); // true | |
console.log( Object.is(NaN, NaN) ); // true | |
console.log( NaN === NaN ); // false | |
// Object.assign | |
let receiver = {}; | |
Object.assign(receiver, { | |
type: "js", | |
name: "file.js" | |
}, { | |
type: "css" | |
}); | |
console.log(receiver.type); // "css" | |
console.log(receiver.name); // "file.js" | |
// ---- ES6 - Method Objects ---- | |
let name22 = "Arni"; | |
let user = { | |
name22, | |
// вместо "sayHi: function() {" пишем "sayHi() {" | |
sayHi() { | |
console.log(this.name22); | |
} | |
}; | |
user.sayHi(); // Arni | |
// ---- ES6 - Symbols ---- | |
let uid = Symbol.for("uid"); | |
let object = { | |
[uid]: "12345" | |
}; | |
console.log(object[uid]); // "12345" | |
console.log(uid); // "Symbol(uid)" | |
let uid2 = Symbol.for("uid"); | |
console.log(uid === uid2); // true | |
console.log(object[uid2]); // "12345" | |
console.log(uid2); // "Symbol(uid)" | |
// ---- ES6 - Sets and Maps ---- | |
// Map | |
let map = new Map(); | |
map.set('1', 'str1'); // ключ-строка | |
map.set(1, 'num1'); // число | |
map.set(true, 'bool1'); // булевое значение | |
// в обычном объекте это было бы одно и то же, | |
// map сохраняет тип ключа | |
console.log( map.get(1) ); // 'num1' | |
console.log( map.get('1') ); // 'str1' | |
console.log( map.size ); // 3 | |
// Set | |
let set = new Set(); | |
let vasya = {name: "Вася"}; | |
let petya = {name: "Петя"}; | |
let dasha = {name: "Даша"}; | |
// посещения, некоторые пользователи заходят много раз | |
set.add(vasya); | |
set.add(petya); | |
set.add(dasha); | |
set.add(vasya); | |
set.add(petya); | |
// set сохраняет только уникальные значения | |
console.log( set.size ); // 3 | |
// ---- Set and Map | |
// SET | |
let numbers = [1, 2, 3, 3, 3, 4, 5]; | |
let noDuplicates = [...new Set(numbers)]; | |
console.log(noDuplicates); // [1,2,3,4,5] | |
let map22 = new Map([["name", "Ivan"], ["age", 35]]); | |
// MAP | |
console.log(map22.has("name")); // true | |
console.log(map22.get("name")); // "Nicholas" | |
console.log(map22.has("age")); // true | |
console.log(map22.get("age")); // 35 | |
console.log(map22.size); // 2 | |
map22.clear(); | |
console.log(map22.has("name")); // false | |
console.log(map22.size); // 0 | |
// ---- ES6 - Sets and Maps ---- | |
let arr = [1, 2, 3]; // массив — пример итерируемого объекта | |
for (let value of arr) { | |
console.log(value); // 1, затем 2, затем 3 | |
} | |
for (let char of "Привет") { | |
console.log(char); // Выведет по одной букве: П, р, и, в, е, т | |
} | |
// default iterator | |
// default iterator | |
let values3 = [1, 2, 3]; | |
let iterator = values3[Symbol.iterator](); | |
console.log(iterator.next()); // "{ value: 1, done: false }" | |
console.log(iterator.next()); // "{ value: 2, done: false }" | |
console.log(iterator.next()); // "{ value: 3, done: false }" | |
console.log(iterator.next()); // "{ value: undefined, done: true }" | |
// ---- ES6 - Generators ---- | |
function* generateSequence() { | |
yield 1; | |
yield 2; | |
return 3; | |
} | |
let generator = generateSequence(); | |
let one = generator.next(); | |
console.log(JSON.stringify(one)); // {value: 1, done: false} | |
let two = generator.next(); | |
console.log(JSON.stringify(two)); // {value: 2, done: false} | |
// Generators and Iterator | |
function* generateSequence() { | |
yield 1; | |
yield 2; | |
return 3; | |
} | |
let generator2 = generateSequence(); | |
for(let value of generator2) { | |
console.log(value); // 1, затем 2 | |
} | |
// ---- | |
function *createIterator() { | |
yield 1; | |
return; | |
yield 2; | |
} | |
let iterator2 = createIterator(); | |
console.log(iterator2.next()); // "{ value: 1, done: false }" | |
console.log(iterator2.next()); // "{ value: undefined, done: true }" | |
// ---- ES6 - Classes ---- | |
class User { | |
constructor(name) { | |
this.name = name; | |
} | |
sayHi() { | |
console.log(this.name); | |
} | |
} | |
let user2 = new User("Arni"); | |
user2.sayHi(); // Arni | |
// getter and setter | |
class PersonClass { | |
constructor(name) { | |
this.name = name; | |
} | |
sayName() { | |
console.log(this.name); | |
} | |
get name() { | |
return this.name; | |
} | |
set name(value) { | |
this.name = value; | |
} | |
} | |
// static | |
class PersonClass2 { | |
constructor(name) { | |
this.name1 = name; | |
} | |
sayName() { | |
console.log(this.name); | |
} | |
get name() { | |
return this.name1; | |
} | |
set name(value) { | |
this.name1 = value; | |
} | |
static create(name) { | |
return new PersonClass2(name); | |
} | |
} | |
let person2 = PersonClass2.create('Arni'); | |
console.log( person2.name1 ); // Arni | |
console.log( person2.create ); // create ... (function) | |
// inheritance | |
class PersonClass3 { | |
constructor(name) { | |
this.name3 = name; | |
} | |
sayName() { | |
console.log(this.name); | |
} | |
get name() { | |
return this.name3; | |
} | |
set name(value) { | |
this.name3 = value; | |
} | |
static create(name) { | |
return new PersonClass3(name); | |
} | |
} | |
class SuperPersonClass extends PersonClass3 { | |
constructor(name) { | |
super(`Super ${name}`); | |
} | |
} | |
let superPerson = new SuperPersonClass('Arni'); | |
// ---- Async and Await ---- | |
// Promise | |
function logFetch(url) { | |
return fetch(url) | |
.then(response => response.text()) | |
.then(text => { | |
console.log(text); | |
}).catch(err => { | |
console.error('fetch failed', err); | |
}); | |
} | |
// Async and Await | |
async function logFetch(url) { | |
try { | |
const response = await fetch(url); | |
console.log(await response.text()); | |
} catch (err) { | |
console.log('fetch failed', err); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Title</title> | |
</head> | |
<body> | |
<script src="es6.js"></script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment