Es2019 Javascript and Its New Features

ES2019 JavaScript and its new features


ECMAScript 2019 has finished and rolled out new exciting features for developers. The proposals which have been accepted and reached stage 4 by the TC39 committee would be included in the specification of that year and the others - are postponed to the next year.

What that’s mentioned above is a part of the TC39 process - which is responsible to make changes and add features to the ECMAScript specification.

  • Stage 0: Strawman
  • Stage 1: Proposals
  • Stage 2: Drafts
  • Stage 3: Candidates
  • Stage 4: Finished/Approved

Here are the links for you can see all the proposals on Stage 0Stage 1 – 3 and Final Stage.

Optional Catch Binding

Until this proposal, the specification forced us to bind an exception variable for the catch clause whether it’s necessary or not:

try {

// trying to use a new ES2019 feature

// which may not be implemented in other browsers

} catch (unused) {

// revert back to old way

}

the unused binding can now be remove.

try {
  ...
} catch {
  ...
}

Subsume JSON

According to ECMAScript specification, an ECMAScript JSON is a superset of JSON, by all means

After parsing, JSON objects are realized as ECMAScript objects. JSON arrays are realized as ECMAScript Array instances. JSON strings, numbers, booleans, and null are realized as ECMAScript strings, Numbers, Booleans, and null (source).

 

But in practice, that’s not entirely true. Whereas JSON strings accepts unescaped U+2028 and U+2029 characters, ECMAScript strings don’t accept:

// This produces invalid ECMAScript String (before ES2019):
eval('"\u2028"');

// This is invalid as well:
eval('"\u2029"');

Note: U+2028 represents LINE SEPARATOR and U+2029 represents PARAGRAPH SEPARATOR.ç

In simple words, this means there’s an inconsistency between valid JSON String and valid ECMAScript String, which could lead to potential bugs and specific handling in order to patch these gaps.

The proposed solution extends the ECMAScript strings so these will accept U+2028 and U+2029.

Symbol Description

Symbols was introduce in ES2015 and has very unique features. In ES2019, it can now provide its given description. Its goal is to avoid indirectly getting the provided description from Symbol.prototype.toString.

const mySymbol = Symbol('myDescription');
console.log(mySymbol); // Symbol(myDescription)
console.log(mySymbol.toString()); // Symbol(myDescription)
console.log(mySymbol.description); // myDescription

Function.prototype.toString – Revision

As we know, the toString method of a Function object doesn’t inherit directly from Object.prototype.toString, but overrides it.

For example:

// Before ES2019, it was depended on the engine:
console.log(function () { console.log('My Function!'); }.toString());

In ES2015, when toString was invoked on a function - one of the following occurred:

  • It returned a string source code representation of the function, depending on the ECMAScript engine.
  • In case the engine couldn’t produce a valid source code string - it returned an eval string that would throw a SyntaxError exception.

The proposed solution distinguishes between the following cases in order to determine the result of toString:

  • In case that’s a user-defined function object, which means, part of the source code - it returns a string containing the code which was used to define the function.
  • In case that’s a built-in function object or bound function object (a function which is created by bindmethod) - it returns a NativeFunction string.
  • In case that’s a callable function object which isn’t user-defined - it returns a NativeFunction string.
  • In case that’s a dynamically generated function object, through the Function and GeneratorFunctionconstructors - it returns a synthesized string of the appropriate code, which is created by the ECMAScript engine.
  • In all other cases, it throws a TypeError exception.

Let’s demonstrate each case:

// User-defined function object
// This prints "function () { console.log('My Function!'); }"
console.log(function () { console.log('My Function!'); }.toString());

// Build-in function object
// This prints "function parseInt() { [native code] }"
console.log(Number.parseInt.toString());

// Bound function object
// This prints "function () { [native code] }"
console.log(function () { }.bind(0).toString());

// Built-in callable function object
// This prints "function Symbol() { [native code] }"
console.log(Symbol.toString());

// Dynamically generated function object #1
// This prints "function anonymous() {}" (using V8 engine)
console.log(Function().toString());

// Dynamically generated function object #2
// This prints the followng (using V8 engine):
// function () { return __generator(this, function (_a) {
//     return [2 /*return*/];
// }); }
console.log(function* () { }.toString());

// This throws a TypeError: "Function.prototype.toString requires that 'this' be a Function"
Function.prototype.toString.call({});

Object.fromEntries

It is a reverse method for Object.entries which can be one of the ways to clone an object.

 

const obj = {
    prop1: 1,
    prop2: 2,
};
 
const entries = Object.entries(obj);
 
console.log(entries); // [ [ 'prop1', 1 ], [ 'prop2', 2 ] ]
 
const fromEntries = Object.fromEntries(entries);
 
console.log(fromEntries); // Object { prop1: 1, prop2: 2 }
 
console.log(obj === fromEntries); // false

Be careful because any embedded object/array is simply being copied by reference.

const obj = {
    prop1: 1,
    prop2: 2,
    deepCopy: {
        mutateMe: true
    }
};
 
const entries = Object.entries(obj);
const fromEntries = Object.fromEntries(entries);
 
fromEntries.deepCopy.mutateMe = false;
 
console.log(obj.deepCopy.mutateMe); // false

String.prototype trimStart and trimEnd

We already have trim method in String prototype which removes spaces between the start and end of the string. However now ES2019 introduced trimStart and trimEnd.

// Trim
const name = "   Codedam ";
console.log(name.trim());   // "Codedam"
 
 
// Trim Start
const description = "   Unlocks Secret Codes ";
console.log(description.trimStart());   // "Unlocks Secret Codes "
 
 
// Trim End
const category = "  JavaScript ";
console.log(category.trimEnd());    // "  JavaScript"

Array.prototype flat and flatMap

flat method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. The depth by default to 1 which flattens the first layer of nested arrays on the array.

const arr = [1, 2, [3, 4, [5, 6]]];
arr.flat(); // [1, 2, 3, 4, [5, 6]]
arr.flat(2); // [1, 2, 3, 4, 5, 6]
 
 
// You can use Infinity to flatten all the nested arrays no matter how deep the array is
 
const arrExtreme = [1, [2, [3, [4, [5, 6, 7, [8, 9]]]]]];
arrExtreme.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

flatMap is similar to flat and related to map in which it maps the array then flattens it afterwards.

 
const arr = ['Codedam', 'is Awsome', '!'];
 
const mapResult = arr.map(item => item.split(' '));
console.log(mapResult); // [ [ 'Codedam' ], [ 'is', 'Awsome' ], [ '!' ] ]
 
const flatMapResult = arr.flatMap(chunk => chunk.split(' '));
console.log(flatMapResult); // ['Codedam', 'is',  'Awsome', '!'];
 

Upcoming Proposals

These are the proposals that have been reached stage 3 and probably will be included in the specification - right after these will be approved completely.

Here’s attached a list for the proposals in this stage:

Summary

We covered today all the proposed which have been approved, at present, and will be included as part of the ECMAScript 2019 specification.

 

 

 

Reference here

 
by Janeth Kent Date: 18-02-2019 javascript ES2019 javascript features javascript news hits : 3143  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.

 
 
 

Related Posts

Validating HTML forms using BULMA and vanilla JavaScript

Today we are going to write about contact forms and how to validate them using JavaScript. The contact form seems to be one of the top features of every basic home…

A FULFILLED PROMISE - Using the FETCH API to make AJAX calls

In this article we talked about what AJAX calls are and how to use them in a traditional way, by using the XMLHttpRequest (XHR) object. In short, thanks to AJAX…

How to use Parallax.js effect on your website

Today, we're going to write about the parallax effect, similar to parallax scrolling, and how to implement it to improve your landing page. In webdev, they say mobile first -…

How to make the website's dark mode persistent with Local Storage, CSS and JS

Recently we wrote about how to do a switchable alternative color mode or theme, a very useful and popular feature to websites. Today’s article is going to be about how…

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

Javascript: what are callbacks and how to use them.

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is…

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

The package managers npm and yarn: main differences

Npm and yarn are package managers that help to manage a project’s dependencies. A dependency is, as it sounds, something that a project depends on, a piece of code that…

The Javascript asign() method to merge and clone objects

In this article, we will be covering Object.assign()method in javascript in detail with examples. A javascript object is a collection of key-value pairs. Keys are also known as properties of object. Keys…

All the javascript functions and methods to manipulate arrays

This article will show that the prominent JavaScript array functions are .map(), .filter(), and .reduce(), and will then go through examples of instances in which .every() and .some() would save…

TypeScript: The evolution of JavaScript

When you're involved in the development of a large project, programming languages like JavaScript don't seem to be the best solution. Their lack of elements such as Language Aids has…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration