JavaScript ES2018 Features With Examples - AkuCode

JavaScript ES2018 Features With Examples


ES2018

        ECMAScript is the standard upon which JavaScript is based, and it's often abbreviated to ES. Discover everything about ECMAScript, and the last features added in ES2018, aka ES9. ES2018 is the latest version of ECMAScript standard. 

what are the new things introduced in it?

Rest/Spread Properties

ES6 introduced the concept of a rest element when working with array restructuring:

const numbers = [1,2,3,4,5]
[first, second, ...others] = numbers

and spread elements:
const numbers = [1,2,3,4,5]
const sum = (a,b,c,d,e) => a+b+c+d+e
const sum = sum(...numbers)

ES2018 introduces the same but for objects.
Rest properties:
const {first, second, ...others } = {first: 1,second: 2,third: 3,fourth: 4,fifth: 5}
first //1
second //2
others // {third: 3,fourth: 4,fifth: 5 }

        Spread properties allow to create a new object by combining the properties of the object passed after the spread operator:
const items = {first, second, ...others }
items //{ first: 1, second: 2, third: 3, fourth: 4, fifth: 5 }

Promise.prototype.finally()

        When a promise is fulfilled, successfully it calls the then() method, one after another. if something fails during this, the then() methods are jumped and the catch() method is executed. finally() allow you to run some code regardless of the successful or not successful execution of the promise:
fetch('file.json')
    .then(Data => data.json())
    .catch(error => console.log(error))
    .finally(() => console.log('finished'))

Regular Expression improvements

        RegExp lookbehind assertions: match a string depending on what precedes it. this is a lookahead: you use ?= to match a string that's followed by a specific substring:

/Roger(?=Waters)/
/Roger(?= Waters)/.test('Roger is my dog') //false
/Roger(?= Waters)/.test('Roger is my dog and Roger Waters is a famous musician') //true

?! perform the inverse operation, matching if a string is not followed by a specific substring:
/Roger(?!Waters)/
/Roger(?! Waters)/.test('Roger is my dog') //true /Roger(?! Waters)/.test('Roger Waters is a famous musician') //false

Lookaheads use the ?= symbol. They were already available.
Lookbeinds, a new feature, uses ?<=
/(?<=Roger) Waters/
/(?<=Roger) Waters/.test('Pink Waters is my dog') //false
/(?<=Roger) Waters/.test('Roger is my dog and Roger Waters is a famous musician') //true

A lookbehind is negated using ?<! :
/(?<!Roger) Waters/
/(?<!Roger) Waters/.test('Pink Waters is my dog') //true
/(?<!Roger) Waters/.test('Roger is my dog and Roger Waters is a famous musician') //false

Unicode Property Escapes \p{...} and \P{...}

        In a regular expression pattern, you can use \d to match any digit, \s to match any character that's not white space, \w to match any alphanumeric character, and so on. This new feature extends this concept to all Unicode characters introducing \p{} and is negation \p{}.
    Any unicode character has a set of properties. For example Script determines the language family, ASCII is a boolean that's true for ASCII characters, and so on. you can put this property in the graph parentheses, and the regex will check for that to be true:
/^\p{ASCII}+$/u.test('abc') //✅
/^\p{ASCII}+$/u.test('ABC@') //✅
/^\p{ASCII}+$/u.test('ABC۽❌

ASCII_Hex_Digit is another boolean property, that checks if the string only contains valid hexadecimal digits:
/^\p{ASCII_Hex_Digit}+$/u.test('0123456789ABCDEF') //✅
/^\p{ASCII_Hex_Digit}+$/u.test('h') //❌

        There are many other boolean properties, which you just check by adding their name in the graph parentheses, including uppercase,lowercase,white_space, alphabetic,emoji and more :
/^\p{Lowercase}$/u.test('h') //✅
/^\p{Uppercase}$/u.test('H') //✅
/^\p{Emoji}+$/u.test('H') //❌
/^\p{Emoji}+$/u.test('۽ ۽✅

        In addition to those binary properties, you can check any of the unicode character properties to match a specific value. In this example, I chck if the string is written in the greek or latin alphabet:
/^\p{Script=Greek}+$/u.test('ελληνικά') //✅
/^\p{Script=Latin}+$/u.test('hey') //✅

Read more about all the properties you can use directly on the proposal.

Named capturing groups


        In ES2018 a capturing group can be assigned to a name, rather than just being assigned a slot in the result array:
const re = /(?\d{4})-(?\d{2})-(?\d{2})/
const result = re.exec('2015-01-02')
// result.groups.year === '2015';
// result.groups.month === '01';
// result.groups.day === '02';

The s flag for regular expressions


        The s flag, short for single line, causes the . to match new line characters as well. without it, the dot matches regular characters but not the new line:
/hi.welcome/.test('hi\nwelcome') // false
/hi.welcome/s.test('hi\nwelcome') // true

Coding Style

        This JavaScript Coding Style is the set of conventions I use every day when using JavaScript. It's a live document, with the main set of rules I follow. A coding style is an agreement with yourself and your team, to keep consistency on a project. An if you don't have a team, it's an agreement with you, to always keep your code up to your standards. Having fixed rules on your code writing format helps a lot in order to have a more readable and managed code.

Popular Style Guides

There are a quite a few of them around, here are the 2 most common ones in the JavaScript world:
It's up to you to follow one of those or create your own style guide.

Be consistent with the project you work on

        Even if you prefer a set of styles, when working on a project you should use that project style. An Open Source project on GitHub might follow a set of rules, another project you work on with a team might follow an entirely different one. Prettier is an awesome tool that enforces code formatting, use it.

My own preferences

    My own take on JavaScript style is:
  • Always use the latest ES version. Use Babel if old browser support is necessary.
  • Indentation: use spaces instead of tabs, indent using 2 spaces.
  • Semicolons: don't use semicolons.
  • Line Length: try to cut lines at 80 chars, if possible.
  • Inline Comments: use inline comments in your code. Use block comments only to document.
  • No dead code: Don't leave old code commented, "just in case" it will be useful later. Keep only the code you need now, version control/you notes app is meant for this.
  • Only comment when useful: Don't add comments that don't help understand what the code is doing. if the code is self-explaining through the use of good variable and function naming, and JSDoc function comment, don't add a comment
  • Variable declarations: always declare variables to avoid polluting the global object. Never use var . Default to const, only use let if you reassign the variable.
  • Constant: declare all constant in CAPS. Use _ to separate words in a VARIABLE_NAME.
  • Functions: use arrow functions unless you have a specific reason to use regular functions, like in object methods or constructors, due to how this works. Declare them as const, and use implicit returns if possible
    const test = (a, b) => a + b
    const another = a => a + 2

    Feel free to use nested functions to hide helper functions to the rest of the code
  • Names: function names, variable names and method names always start with a lowercase letter (unless you identify them as private, read below), and are camelCased. Only constructor functions and class names should start capitalized. if you use a framework that requires specific conversations, change your habits accordingly. File names should all be lowercase, with word separated by -.
  • Statement-specific formats and rules:
    If
    if (condition) {
        statements
    }
    if (condition) {
        statements
    } else {
        statements
    }
    if (condition) {
        statements
    } else if (condition) {
        statements
    } else {
        statements
    }

    For
    Always initialize the length in the initialization to cache it, don't insert it in the condition. Avoid using for in except with used in conjuction with .hasOwnProperty(). Prefer for of.
    for (initialization; condition; update) {
        statements
    }

    While
    while (condition) {
        statements
    }

    do
    do {
        statements
    } while (condition);

    switch
    switch (expression) {
      case expression:
        statements
      default:
    statements
    }

    try
    try {
        statements
    } catch (variable) {
        statements
    }
    try {
        statements
    } catch (variable) {
        statements
    } finally {
        statements
    }

  • Whitespace: use whitespace wisely to improve readability: put a whitespace after a keyword followed by a ( ; before 7 after a binary operation n ( + , - , / , * , && ..); inside the for statement, after each ; to separate each part of the statement; after each ,.
  • New lines: use newlines to separate blocks of code that perform logically related operations.
  • Quotes favor single quotes ' instead of double quotes ". Double quotes are a standard in HTML attributes, so using single quotes helps remove problem when dealing with HTML strings. Use template literals when appropriate instead of variable interpolation.
Comments