Which new functions are added in ES6

ECMAScript 6 - the future of JavaScript?

JavaScript (JS) has been an everyday companion for web developers for years, be it in the frontend or backend. As a scripting language for the browser, JavaScript is also used for other areas of application, such as B. Node.js.

For us, too, working with JavaScript is an important part of professional life. For example, Shopware 6 relies on the Vue.js. framework for the administration interface in the backend. In the front end, the approach “to forego jQuery” is used and, if possible, everything is implemented in pure JavaScript, “Vanilla JavaScript”. Thanks to the ECMAScript 6 or ES6 standard and its updates, the programming language offers interesting functions that make work easier.

What is ECMAScript?

ECMAScript describes the standard for JavaScript. All modern browsers have supported version 5.1 since 2012. Today we will take a look at version 6 and its successors, which receive an update every year. The problem with working with the new features is that some browsers may not be able to use the specs yet. It's worth taking a look at browser compatibility. If for a customer project z. If, for example, it is clear that the focus is also on Internet Explorer 11, an alternative to modern JavaScript must be created.

With Babel it is possible to compile a JavaScript that is compatible with all browsers. This can be particularly useful for versions of ECMAScript 2015 and more modern variants. When developing a Shopware 6 project, the written JS can also be converted directly into code that is understandable for older browsers thanks to a built-in compiler. Very cool! In order not to go beyond the scope, I will not go into the establishment of Babel here.

Useful examples

The easiest way to illustrate the advantages of ES6 is to demonstrate it with a few examples. If you already have experience with the version of JS, you shouldn't find out much that is new, as this is only a small overview. Enough of the words, let's go!

let and const

No more variables that could be overwritten undesirably. Thanks to the keyword let is the variable in blockscope. One block is e.g. B. an If loop. In the past one could with var declared variable in a loop can also be called outside of it. Now the variable created in a block remains “hidden” outside of this block. Let Also does not overwrite any variables outside the block that have the same name.

var a = 0; console.log (a); if (condition) {let a = 1; console.log (a); } console.log (a); // 0 // 1 // 0 if (condition) {let a = 'test'; console.log (a); } console.log (a); // test // Uncaught ReferenceError: a is not defined

There is another way of declaring variables. With const a constant can be created that cannot be reassigned. Otherwise behaves const as well as let, is so blockscoped.

Arrow functions

Features got with the new arrow functions an alternative syntax. It can function and return Keyword can be omitted and also the curly braces. However, this is only the case if the function has only one parameter and the function content only returns one value. What needs to be considered arrow functions don't have their own this. Besides, they're not dated hoisting affected, that means they have to be defined before they are called.

// old syntax let greeting = function (name) {console.log (`Hello $ {name}!`); } // new syntax let greeting = (name) => {console.log (`Hello $ {name}!`); } // new syntax // omit parenthesis if only one parameter exists // omit return keyword if statement has only return expression let doubleValue = value => value * 2; console.log (doubleValue (42));

Classes in ECMAScript

With ES6, classes were introduced as templates for JavaScript objects. The big advantage is that the new syntax is more catchy and easier to understand. With the help of class classes are created. The class also needs a constructor Method that is called automatically when a new object is created. Will not constructor Method specified, then JS adds an empty constructor added. Class methods are defined using the same syntax as object methods.

class Pokemon {constructor (name, type) {this.name = name; this.type = type; }} let pikachu = new Pokemon ("Pikachu", "Electric");

Default parameters

At last! In JS it is possible to define a standard value for parameters. Instead of an additional query in the function, such as For example, a default parameter can be specified in PHP. The annoying checking of whether a parameter actually exists is no longer necessary.

// old version function multiply (factorOne, factorTwo) {factorTwo = (typeof factorTwo! == 'undefined')? factorTwo: 1; return factorOne * factorTwo; } // new version function multiply (factorOne, factorTwo = 1) {return factorOne * factorTwo; }

One promise is not broken: Promises

Promises work much like promises in real life. A promise is made for the future. This should apply, but can also not occur due to changed circumstances. That also applies to Promises in JS. As long as one Promise has not been resolved, is the status pending. If the promise could be kept, he is resolved and if not, then the traffic jam rejected. A request to a server is used as an example. As long as the request is running, this is pending and if the desired data comes back, it will Promiseresolved. Promises are therefore objects that return the result of asynchronous actions if the promise has been kept. If this is not the case, an error is pointed out.

Promises are using the constructor new promise creates and contains a function as a parameter. This has the variables resolve and reject as a parameter. If an action is deemed successful then it will resolve executed, otherwise reject. On a Promise can now then and catch appended to catch one of the two cases mentioned. Let's look at an example in the code.

const myPromise = new Promise ((resolve, reject) => {// some functionality // api calls or something if (condition) {resolve ('Promise is resolved successfully');} else {reject ('Promise is rejected') ;}}); // if promise is resolved true then function is called otherwise catch myPromise.then ((message) => {console.log (message);}). catch ((message) => {console.log (message);}) ;

Wait with Async / Await

With the 2017 version of ECMAScript there was a further improvement in asynchronous programming in JavaScript. A function with the async Keyword marked. A function would in this case e.g. B. not return a value, but a Promise. The result can only be in connection with the await Keyword to be seen. Await can only be in a function that is with async has been defined. If the code reaches the point with the await, is waited until there is a return value. Only then does it continue. For more information, I recommend this article.

function waitASecond (x) {return new Promise (resolve => {setTimeout (() => {resolve (x);}, 1000);}); }; let add = async function (x) {// async function expression assigned to a variable let a = await waitASecond (10); // waits until waitASecond finished return x + a + b; }; add (100) .then (v => {console.log (v); // prints 110 after 1 second.});

Template strings

Putting together strings in JavaScript can be an annoying task. Readability suffers from the sheer number of plus and quotation marks.

console.log ('Hello' + someNameVariable + '! Today is' + someDateVariable + '.');

It would be better to use variables directly in the string, right? There are template strings or template literals. The string is simply surrounded by backticks (“). You can now use the syntax $ (variableName) be used. Bye bye, plus sign.

console.log (`Hello $ {someNameVariable}! Today is $ {someDateVariable} .`);

Destructuring

It's now easier to take apart arrays and objects. Variables can easily be assigned values ​​from arrays or objects. To explain it simply, here is an example from the Shopware code.

// Component is qual to Shopware.Component and Mixin to Showpare.Mixin const {Component, Mixin} = Shopware;

The object contains ShopwareComponent and Mixin. Thanks to the Destructurings can be stored directly in a variable without much code.

Conclusion

Maybe that was a lot, but it wasn't all. I just scratched the surface with the information. ES6 and all other updates brought many exciting new features to the JavaScript world. Functions like includes, isNaN or Spread and rest Operators are just other options that can be used and make everyday work easier.

If you feel like learning more about the topic, you are welcome to follow the sources listed below and deepen your knowledge.

Do you already have experience in JavaScript and are you looking for a new job? Then take a look at our vacancies.