Nový Javascript

ES2015, ES2016,

ES2017, ES2018

ES?

ECMAScript

ECMAScript

Oficiálny názov JavaScriptu

Java® je ochranná známka

ECMA

European Computer Manufacturers Association

ES2015 vs. ES6

  • Harmony
  • ES6
  • ES2015

Novinky ES2015

Na skúšanie potrebujete

node 9.11.2 a vyšší

Alebo

Ukážeme si babel, lebo ním v Profesii transpilujeme kód pre web

Inštalácia

mkdir novy-js

cd novy-js

mkdir src
mkdir public

yarn add --dev babel-cli babel-preset-env

Konfigurácia

{
   // ...
   "scripts": {
     "build": "babel src -d dist",
     "watch": "babel --watch src -d dist"
   },
   // ...
}

package.json:

{
    "presets": ["env"]
}

.babelrc:

Spustenie

// vytvote subor src/subor.js

yarn run build

node dist/subor.js

Literály pre binárne a oktálové čísla

var x = 0b1011;

var y = 0o715;

Deklarácia premenných

  • let

  • const

Dva nové spôsoby deklarácie

Blokový scope

let foo = 'foo';

foo = 'foo 2';

// ----

const bar = ['pivo'];

bar.push('vino');

bar = ['borovicka']; // TypeError: invalid assignment
                     // to const `bar`





Arrow funkcie

  • kratší zápis
  • uchovávanie kontextu (this, arguments)

Arrow funkcie - kratší zápis

var pow = function (arg) {
    return arg * arg;
};
const pow = (arg) => {
    return arg * arg;
};
const pow = (arg) => arg * arg;
// Pozor, zátvorky okolo argumentov sa dajú odobrať
// iba v prípade jednoargumentovej funkcie
// Funkcia bez argumentov musí mať zátvorky uvedené!
const getName = () => 'zelenina';
const pow = arg => arg * arg;

Arrow funkcie - zdieľanie kontextu

const tyrion = {
    name: 'tyrion',
    tags: ['piť', 'nadávať', 'veci'],

    printKnowledge: function () {
        this.tags.forEach(function (tag) {
            console.log(this.name + ' vie ' + tag);
        });
    }
};

tyrion.printKnowledge();

Arrow funkcie - zdieľanie kontextu

const tyrion = {
    name: 'tyrion',
    tags: ['piť', 'nadávať', 'veci'],

    printKnowledge: function () {
        const that = this;

        this.tags.forEach(function (tag) {
            console.log(that.name + ' vie ' + tag);
        });
    }
};

tyrion.printKnowledge();

Arrow funkcie - zdieľanie kontextu

const tyrion = {
    name: 'tyrion',
    tags: ['piť', 'nadávať', 'veci'],

    printKnowledge: function () {
        this.tags.forEach((function (tag) {
            console.log(this.name + ' vie ' + tag);
        }).bind(this));
    }
};

tyrion.printKnowledge();

Arrow funkcie - zdieľanie kontextu

const tyrion = {
    name: 'tyrion',
    tags: ['piť', 'nadávať', 'veci'],

    printKnowledge: function () {
        this.tags.forEach((tag) => {
            console.log(this.name + ' vie ' + tag);
        });
    }
};

tyrion.printKnowledge();

Rozšírené objektové literály

const name = 'Ferko';
const lastName = 'Mrkvička';
const x = 'abc';
const y = 'def';

const fero = {};

/* Pre objekt fero:
 * - vytvorte property name a lastName,
 *   ktoré budú mať hodnoty z premenných vyššie
 * - vytvorte metódu foo, ktorá vráti reťazec 'metóda foo'
 * - vytvorte property, ktorej názov je poskladaný z x a y.
 */

console.log(fero.name);
console.log(fero.lastName);
console.log(fero.foo());
console.log(fero.abcdef);

Rozšírené objektové literály

const name = 'Ferko';
const lastName = 'Mrkvička';
const x = 'abc';
const y = 'def';

const fero = {
    name: name,
    lastName: lastName,
    
    foo: function () {
        return 'metóda foo';
    },
}

fero[x + y] =  'počítaná property';

console.log(fero.name);
console.log(fero.lastName);
console.log(fero.foo());
console.log(fero.abcdef);

Rozšírené objektové literály

const name = 'Ferko';
const lastName = 'Mrkvička';
const x = 'abc';
const y = 'def';

const fero = {
    name,
    lastName,
    
    foo() {
        return 'metóda foo';
    },
    
    [x + y]: 'počítaná property',
};

console.log(fero.name);
console.log(fero.lastName);
console.log(fero.foo());
console.log(fero.abcdef);

Destructuring - polia

const [x, y] = [1, 2];

const pole = ['agát', 'blýskavica', 'cieľovníci'];

const [a, , c] = pole;

const [foo, bar, baz = 33] = [11, 22];

// výmena hodnôt dvoch prvkov

let [var1, var2] = ['value 1', 'value 2'];

[var2, var1] = [var1, var2];

Destructuring - objekty

const obj = {
    foo: 1,
    bar: 2,
    baz: 3,
};

const { foo, baz } = obj;

// prípadne pod iným názvom
const { foo: aliasFoo, baz } = obj;

// default hodnoty

const {foo, xyz = 42} = obj;

Destructuring - objekty

// argumenty funkcie

const params = {
    logger: 'console',
    isDev:  true,
};

foo(params);

const foo = function ({ isDev, logger }) {
    console.log(logger);
    console.log(isDev);
};

Default hodnoty argumentov funkcie

const foo = function (x, y = 5) {
    // ...
};

const bar = (x, y = 5) => {
    // ...
};

Rest operátor

const foo = (x, ...y) => {
    console.log(y);
};

foo(1, 2, 3, 4, 5);

Spread operátor

const foo = (x, y, z) => {
    console.log(x, y, z);
};

const arr = [1, 2, 3];

foo(...arr);

Template string

const multiline = `toto je viacriadkový
reťazec
`;

console.log(multiline);

const str = 'reťazec';
const val = 'hodnotami';

const replaced = `toto je ${str} s nahradenými ${val}`;

console.log(replaced);

for-of cyklus

const arr = [1, 2, 3, 4, 5];

for (const i of arr) {
    console.log(i);
}
const foo = function* () {
    yield 1;
    yield 2;
}

for (const i of foo()) {
    console.log(i);
}
const str = 'hello world';

for (const c of str) {
    console.log(c);
}

Generátory

const gen = function* () {
    let n = 1;

    while (true) {
        yield n;
        n++;
    }
}

const generator = gen();

console.log(generator.next());

Iterátory

const cart = {
    price: 23.5,
    items: ['jablko', 'hruska', 'banan'],

    [Symbol.iterator]: function* () {
        let i = 0;

        while (i < this.items.length) {
            yield this.items[i];
            i++;
        }
    }
};

for (const i of cart) {
    console.log(i);
}

Unicode

Plná podpora Unicode v reťazcoch a regulárnych výrazoch

Rozšírenia pre Number

Number.EPSILON

Number.isInteger(Infinity)

Number.isNaN(NaN)

String.prototype.includes a String.prototype.repeat

"ferko mrkvička".includes("mrk");

"abc".repeat(3);

Object.assign

let person = {id: 42};

person = Object.assign(
    person,
    {
        name: 'fero',
    },
    {
        name: 'jozo',
        surname: 'mrkvicka',
    },
    {
        name: 'ferko',
    }
);

Rozšírenia pre Array

Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']

Array.from([1, 2, 3]); // [1, 2, 3]

Array.from([1, 2, 3], x => x + 10); // [11, 12, 13]

// -----

Array.of(1, 2, 3); // [1, 2, 3]

Rozšírenia pre Array.prototype

const arr = [0, 0, 0, 0]

arr.fill(7, 1, 2);

console.log(arr); // [0, 7, 0, 0]

// ---

const idx = arr.findIndex(x => x == 7);

console.log(idx); // 1

Rozšírenia pre Array.prototype

const arr = ['a', 'b', 'c'];

for (const i of arr.entries()) {
    console.log(i);
}

for (const i of arr.keys()) {
    console.log(i);
}

for (const i of arr.values()) {
    console.log(i);
}

Nové metódy entries, keys a values, ktoré vracajú iterátor.

Niekedy nabudúce

  • Promise
  • Triedy
  • Moduly
  • ES 2016
  • ES 2017
  • ES2018

Ďakujem za pozornosť

Otázky?

Nový Javascript

By Milan Herda

Nový Javascript

  • 553