ECMAScript 2021

JavaScript – ECMAScript 2021 ”; Previous Next The ECMAScript 2021 standard was released in 2021. ECMAScript 2021 brought many notable features to JavaScript. The introduction of the String replaceAll() method simplified global string replacement. Logical Assignment Operators, (&&=, ||=, and ??=), enhanced code conciseness. This update focused on improving developer productivity and code readability. This chapter will discuss all the newly added features in ECMAScript 2021. New Features Added in ECMAScript 2021 Here are the new methods, features, etc., added to the ECMAScript 2021 version of JavaScript. Numeric Separators (_) Promise any() method String replaceAll() method Logical AND Assignment Operator (&&=) Logical OR Assignment (||=) Nullish Coalescing Assignment (??=) Here, we have explained each feature in detail. Numeric Separators (_) ECMAScript 2021 introduced numeric separators. The numeric seprators are used to make the number more readable. Example We added a numeric separator in the code below to make the number more readable. <html> <body> <div id = “output”>The value of the num is: </div> <script> let num = 90_00_000; document.getElementById(“output”).innerHTML += num; </script> </body> </html> Output The value of the num is: 9000000 Promise any()Method ECMAScript 2021 introduced Promise any() method. The promise.any() method fulfills any promise from the array of promises, which resolves at the earliest. Example In the below code, we have created multiple promises and passed them as an argument of the Promise.any() method. We have resolved the promise1 and rejected the promise2. For the Promise.any() method, JavaScript control goes into the then() block as promise1 gets resolved. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(“demo”); const promise1 = new Promise((res, rej) => res()); const promise2 = new Promise((res, rej) => rej()); const promises = [promise1, promise2]; Promise.any(promises) .then(() => { output.innerHTML += ”One or more promises are resolved!”; }) .catch((err) => { output.innerHTML += ”All promises are rejected:” + err; }); </script> </body> </html> Output One or more promises are resolved! String replaceAll() Method The ECMAScript 2021 introduced String replaceAll() method to the Strings. The string replaceAll() method is used to replace the particular substring with another substring. The replaceAll() method takes either string or regular expression as a parameter. Example In the below code, we have replaced the lowercase ”a” with the uppercase ”A” using the replaceAll() method. <html> <body> <div id = “output1”>Original string is: </div> <div id = “output2”>Updated string is: </div> <script> let str = “abcd abcd abcd abcd”; document.getElementById(“output1”).innerHTML += str; let updatedStr = str.replaceAll(“a”, “A”); document.getElementById(“output2″).innerHTML += updatedStr; </script> </body> </html> Output Original string is: abcd abcd abcd abcd Updated string is: Abcd Abcd Abcd Abcd Logical AND Assignment Operator (&&=) Operator ECMAScript 2021 introduced the logical assignment operators (&&=, ||= and ??=) to the operators. The JavaScript logical AND Assignment operator updates the value of the first operand with the second operand if the first operand is true. Example In the code below, the str string”s value is not falsy. So, it updates the value of an str variable with ”Hi”. <html> <body> <div id = “output”>The value of the str is: </div> <script> let str = “Hello”; str &&= “Hi”; document.getElementById(“output”).innerHTML += str; </script> </body> </html> Output The value of the str is: Hi Logical OR Assignment (||=) Operator ECMAScript 2021 introduced the logical OR Assignment operator to operators. It updates the value of the first operand with the second operand if the first operand is false. Example In the code below, the initial value of the str is false. So, the Logical OR assignment operator updates its value with the second operand, which is 10. <html> <body> <div id = “output”>The value of the str is: </div> <script> let str = false; str ||= 10; document.getElementById(“output”).innerHTML += str; </script> </body> </html> Output The value of the str is: 10 Nullish Coalescing Assignment (??=) Operator The ECMAScript 2021 introduced the nullish coalescing assignment operator to operators. This operator updates the value of the left operand if it is undefined or null. Example In the below code, the value of the str variable is null. So, the nullish coalescing assignment operator assigns the ”default” value to the str variable. <html> <body> <div id = “output”>The value of the str is: </div> <script> let str = null; str ??= “default”; document.getElementById(“output”).innerHTML += str; </script> </body> </html> Output The value of the str is: default Warning – Some of the above features are not supported by some browsers. So, you can use the polyfill to avoid errors. Print Page Previous Next Advertisements ”;

ECMAScript 2017

JavaScript – ECMAScript 2017 ”; Previous Next The ECMAScript 2017 version of JavaScript was released in 2017. ECMAScript 2017 introduced a number of new features to the language. One the most notable features is async/await syntax which allows us to write asynchronous operations in a more synchronous style. It provided shared memory and atomics that enhances support for concurrent programming. In this chapter, we will discuss all the new added features in ECMAScript 2017. New Features Added in ECMAScript 2017 Here are the new methods, features, etc., added to the ECMAScript 2017 version of JavaScript. padStart() and padEnd() methods Object.entries() method Object.values() method JavaScript async and await Object getOwnPropertyDescriptors() Method JavaScript Shared Memory Here, we have explained each feature in detail. String Padding: padStart() and padEnd() methods The ECMAScript 2017 introduced two string methods, padStart() and padEnd() methods, that allow you to add padding to the string at the start and end by adding a particular character. These methods are used to extend the string and achieve the desired length. Example In the below code, we have passed the desired string length as the first parameter of the padStart() and padEnd() method and the character as a second parameter. However, you can also pass the string as a second parameter. <html> <body> <div id = “output1”>After padding at the start: </div> <div id = “output2”>After padding at the end: </div> <script> let base = “TurorialsPoint”; let start_updated = base.padStart(18, “@”); // Padding at the start let end_updated = base.padEnd(18, “*”); // Padding at the end document.getElementById(“output1”).innerHTML += start_updated; document.getElementById(“output2”).innerHTML += end_updated; </script> </body> </html> Output After padding at the start: @@@@TurorialsPoint After padding at the end: TurorialsPoint**** The Object.entries() Method ECMAScript 2017 added Object.entries() method to objects. The Object.entries() method returns an iterator to traverse the key-value pair of the object. Example In the below code, the employee object contains three properties. We used the Object entries() method to get the iterator of the object. After that, we used the for…of loop to traverse object properties using the iterator. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(“demo”); const employee = { Company: “TutorialsPoint”, Ex_company: “TCS”, Experience: 4, } const emp_iterator = Object.entries(employee); for (let pair of emp_iterator) { output.innerHTML += pair + “<br>”; } </script> </body> </html> Output Company,TutorialsPoint Ex_company,TCS Experience,4 The Object.values() Method ECMAScript 2017 introduced Object.values() method to objects. The JavaScript Object.values() method is used to get the array of values of the object properties. Example In the below code, we used the Object.values() method to get all the values of the object in the array. <html> <body> <div id = “output”>Object values are: </div> <script> const wall = { color: “blue”, size: “15×12”, paintBrand: “Asiant paints” } document.getElementById(“output”).innerHTML += ” ” + Object.values(wall); </script> </body> </html> Output Object values are: blue,15×12,Asiant paints JavaScript async and await The async and await keywords are added to the language in ECMAScript 2017. The async/await keywords are used to create asynchronous functions. The async keyword is used to create asynchronous functions, and await keyword handles the operations. Example The printMessage() function is asynchronous in the below code. We have defined a new promise inside the function and stored it in the getData variable. The promise takes the time of 0.5 seconds to resolve. The ‘await’ keyword handles the promise and blocks the function code execution until the promise gets resolved. <html> <body> <div id = “output”> </div> <script> async function printMessage() { let getData = new Promise(function (res, rej) { setTimeout(() => { res(“Promise resolved !!”); }, 500); }); document.getElementById(“output”).innerHTML = await getData; } printMessage(); </script> </body> </html> Output Promise resolved !! The Object.getOwnPropertyDescriptors() Method The Object.getOwnPropertyDescriptor() method returns the property descriptors for each property, such as writable, enumerable, configurable, value, etc. It is metadata for the object property. Example In the below code, we get the property descriptors for each property of the object using the getOwnPrpopertyDescriptors() method. <html> <body> <div id = “output”>The Property descriptors of the wall object is: <br></div> <script> const wall = { color: “blue”, thickness: 10, } document.getElementById(“output”).innerHTML += JSON.stringify(Object.getOwnPropertyDescriptors(wall)); </script> </body> </html> Output The Property descriptors of the wall object is: {“color”:{“value”:”blue”,”writable”:true,”enumerable”:true,”configurable”:true},”thickness”:{“value”:10,”writable”:true,”enumerable”:true,”configurable”:true}} JavaScript Shared Memory and Atomics In JavaScript, share memory allows multiple threads to share a memory, enabling efficient communication between multiple threads. JavaScript is a single-threaded programming language. However, you can use the web workers to run the JavaScript code in the different threads. In 2018, SharedArrayBuffer was introduced to share memory and perform atomic operations by sharing the data. Print Page Previous Next Advertisements ”;

JavaScript – History

JavaScript – History ”; Previous Next JavaScript has changed the website, application, and game development world and revolutionized the digital industry. JavaScript is mainly used with HTML and CSS to develop the application interface. However, nowadays, it is also used as a server-side programming language. In the world, according to stackoverflow survey 2023, around 63% of developers are using JavaScript. History of JavaScript Let”s discuss a brief history of JavaScript. First stage development of JavaScript In 1993, Some developers released the web browser Mosaic, with a graphical interface. In 1994, Netscape was founded by the lead developers of the Mosaic web browser. They have also released the browser named Netscape Navigator. Till 1996, websites were static, containing only HTML and CSS. So, dynamic behavior needed to be added to the web page to make the website more interactive. The scripting language is required to add the dynamic behavior to the web page. Netscape”s lead software developer, Brendan Eich, developed the scripting language in September 1995 within 10 days. ”Mocha” name was given to the newly developed scripting language and renamed later to ”LiveScript” and then ”JavaScript”. The name JavaScript is given from the ”Java” language. Java was the most popular language in those days, and the script was added due to the scripting language. Standardization of JavaScript JavaScript was only supported by the Internet Explorer browser when it was developed. However, the internet explorer browser is deprecated now. In 1997, to promote JavaScript across all web browsers, Netscape submitted a proposal to the European Computer Manufacturers Association (ECMA) for standardizing JavaScript. This is how ECMAScript(ES) came into the world of development. After that, the JavaScript developer”s community and Netscape update the JavaScript continuously, adding new features to the JavaScript and releasing the new version, ES1, ES2, …, ES13, etc. The latest version of JavaScript is ES13. JavaScript Libraries and Frameworks After 2005, a revolution came into JavaScript development. In 2006, one of the most popular libraries, JQuery, was developed to make website development more accessible. However, JavaScript supports thousands of libraries nowadays. In 2010, frameworks like Ember, Backbone, etc., were introduced. The framework provides the structure of the application. In 2013, one of the most popular frameworks named, React, was introduced. Server-side JavaScript In 2009, the NodeJS runtime environment was introduced by Ryan Dhal to create server-side applications. Due to NodeJS, developers can use JavaScript for full-stack web development, and JavaScirpt is not limited to front-end development. Currently, Google is managing NodeJS. Modern JavaScript and ES6 Release In 2015, the ES6 version of JavaScript was released. In the Es6 version, JavaScript developers have significantly changed JavaScript and added more advanced features. The latest version of JavaScript Es13 was released in 2022. History table of JavaScript Year ECMAscript Version Feature Released 1995 Brendan Eich has developed JavaScript. 1996 JavaScript 1.0 was released. 1997 ES1 Standardization of JavaScript occurred by ECMA, and the ES1 version was released. 1998 ES2 ES2 version of JavaScript released. 1999 ES3 ES3 version of JavaScript released. 2006 The first library, JQuery developed to use JavaScript. 2008 ES4 ES4 version of JavaScript released. 2009 NodeJS was developed for the server-side programming language. 2009 ES5 ES5 version of JavaScript released. 2010 The first framework, Angular JS, was developed. 2013 The most popular JavaScript framework, ReactJS developed. 2015 ES6 ES6 version of JavaScript released. 2016 ES7 ES7 version of JavaScript released. 2017 ES8 ES8 version of JavaScript released. 2018 ES9 ES9 version of JavaScript released. 2019 ES10 ES10 version of JavaScript released. 2020 ES11 ES11 version of JavaScript released. 2021 ES12 ES12 version of JavaScript released. 2022 ES13 ES13 version of JavaScript released. Future of JavaScript In the world, 98% of websites use JavaScript as a client-side programming language. The increasing demand for websites, applications, software, etc., also increases the demand for JavaScript. As time passes, the developer”s community develops more libraries and frameworks supported by JavaScript, making it easier to develop the digital product. There are 14+ million JavaScript developers in the world, and the number is growing. Overall, the future of JavaScript is bright. JavaScript Browser Support Most modern browsers support JavaScript. Chrome Firefox Microsoft Edge Opera Safari Firefox Android Yes Yes Yes Yes Yes Yes Print Page Previous Next Advertisements ”;

JavaScript – Versions

JavaScript – Versions ”; Previous Next JavaScript was developed by Brendan Eich in 1995. It was standardized in 1997 by European Computer Manufacturers Association (ECMA) and officially known as ECMAScript. The first version of the language is known as ECMSScript 1 (abbreviated as ES1). The fist three versiosn (ES1, ES2, and ES3) laid the foundation of the language. The fourth version, ES4, was abandoned. The first main revision done in ES5(2009). The second major revised version is ES6 (ECMAScript 2015). After 2015, the versions are named by the year in which it it released. The latest version of JavaScript is ECMAScript 2023. JavaScript Versions In the Below table, we have specified detailed information about each version. Version Official Name Release Year Features Added ES1 ECMAScript 1 1997 First release ES2 ECMAScript 2 1998 Minor changes ES3 ECMAScript 3 1999 Added regular expressions Added do-while Added switch Added try/catch ES4 ECMAScript 4 Never Released. ES5 ECMAScript 5 2009 JavaScript strict mode Multiline strings String.trim() Array methods Object methods Getters and setters Trailing commas ES6 ECMAScript 2015 2015 let and const statements Map and set objects Arrow functions For/of loop Some array methods Symbol Classes Promises JavaScript Modules New Number methods and properties For/of loop Spread operator ES7 ECMAScript 2016 2016 Exponential (**) operator Array.includes() method ES8 ECMAScript 2017 2017 Added Async/await Added Object.entries() method Added Object.values() method Added Object.getOwnPropertyDescriptor() method Added string padding ES9 ECMAScript 2018 2018 Rest object properties JavaScript shared memory Promise.finally() method New features of the RegExp() object ES10 ECMAScript 2019 2019 String trim.start() String trim.end() Array.flat() Revised Array.sort() Revised JSON.stringify() / toString() Object.fromEntries() method ES11 ECMAScript 2020 2020 Nullish Coalescing Operator (??) BigInt primitive data type ES12 ECMAScript 2021 2021 String.replaceAll() method Promise.Any() method ES13 ECMAScript 2022 2022 The static block inside the class New class features Top-level await ES14 ECMAScript 2023 2023 Array findLast() & findLastIndex() Hashbang Grammer Symbols as WeakMap keys Since 2016, early update is being released with version named by the year of release. The update release in June 2023 is known as ECMAScript 2023. Browser Support All modern browsers fully support the ES1 to ES6. For other versions, you may use Polyfill and write the additional code. Chrome Firefox Microsoft Edge Opera Safari Firefox Android Yes Yes Yes Yes Yes Yes Print Page Previous Next Advertisements ”;

JavaScript – Proxies

JavaScript – Proxies ”; Previous Next Proxy in JavaScript The JavaScript proxies are objects that allow you to wrap a particular object and customize the fundamental operations of the object, like getting and setting object properties. In short, using the proxy object, you can add custom behavior to the object. The proxies are used to implement features such as logging, caching, and securities. We can create a proxy object using the Proxy() constructor in JavaScript. The constructor accepts two parameters – target object and handler object. It returns a new proxy object for the target object. Syntax Following is the syntax to create a proxy object in JavaScript − const obj = new Proxy(targetObj, Handler); We used the Proxy() constructor with a new keyword in the above syntax. Parameters The Proxy constructor takes two parameters. targetObj − It is a target object for which you want to create a proxy object and customize its default behavior. Handler − It is an object containing the functionality to customize the behavior of the target object. Example In the example below, the person object contains the name and age property. We have defined the proxy object for the person object named proxyObj. Also, we passed the handler object as a Proxy() constructor parameter. In the handler object, we have defined the getters to access the object property. The getters check whether the object contains the property you are looking for. If yes, it returns the property value. Otherwise, it returns the message saying the object doesn”t contain the property. <html> <body> <div id = “demo1”>The name of the person is: </div> <div id = “demo2”>The height of the person is: </div> <script> const person = { name: “Same”, age: 32, } const handler = { // Defining the getters get: function (object, property) { return object[property] ? object[property] : ”Object doesnt contain the property.”; } } const proxyObj = new Proxy(person, handler); document.getElementById(“demo1”).innerHTML += proxyObj.name; document.getElementById(“demo2″).innerHTML += proxyObj.height; </script> </body> </html> Output The name of the person is: Same The height of the person is: Object doesnt contain the property. When you access the non-existing property from the object, it returns the undefined. Here, we have customized the object”s default behavior to return a nice and readable method. If you pass the empty handler object while creating the proxy object, the proxy object will work the same as the original object. JavaScript Proxy Handlers There are multiple proxy handlers available in JavaScript, and we have covered some of them below. The proxy handlers are used to override the default behavior of the object. The JavaScript get() proxy handler The get() proxy handler in JavaScript allows you to change the property accessing behavior of the object. Syntax Follow the syntax below to use the get() proxy handler with the proxy object. get(target, property, receiver) Parameters target − It is a target object. property − It is a property whose value is needed to access. receiver − It is a proxy object itself. Example In the below code, the watch object contains the brand, color, and price property. We have created the proxy for the watch object. The handler object contains the get() handler and returns the property value if it is not. Otherwise, it returns a readable message. <html> <body> <div id = “output1”>Brand: </div> <div id = “output2”>Price: </div> <script> const watch = { brand: “Casio”, color: “Blue”, price: null, } const handler = { get(object, property) { return object[property] != null ? object[property] : “Property is null.”; } } const wathcProxy = new Proxy(watch, handler); document.getElementById(“output1”).innerHTML += wathcProxy.brand; document.getElementById(“output2″).innerHTML += wathcProxy.price; </script> </body> </html> Output Brand: Casio Price: Property is null. The JavaScript set() proxy handler The set() proxy handler in JavaScript is used to change the default behavior of updating the property of the object. Syntax Follow the syntax below to use the set() proxy handler. set(target, property, value, receiver) Parameters target − It is a target object. property − It is a property to change its value. value − It is an updated value. receiver − It is a proxy object itself. Example In the below code, the handler object contains the set() proxy handler. The set() handler checks whether the property is equal to the ”price’. If yes, it updates the property value with a new value. Otherwise, it sets ”Not Available” to the object property. <html> <body> <p id = “demo”> </p> <script> const output = document.getElementById(“demo”); const watch = { brand: “Casio”, color: “Blue”, price: null, } const handler = { set(object, property, value) { if (property === “price”) { object[property] = value; } else { object[property] = “Not Available”; } } } const wathcProxy = new Proxy(watch, handler); wathcProxy.price = 2000; wathcProxy.dial = “Round”; output.innerHTML += “Price: ” + wathcProxy.price + “<br>”; output.innerHTML += “Dial: ” + wathcProxy.dial + “<br>”; </script> </body> </html> Output Price: 2000 Dial: Not Available The JavaScript apply() proxy handler The apply() proxy handler is used to change the default behavior of the function call. Syntax Follow the syntax below to use the apply() proxy handler. apply(target, thisArg, arguments) Parameters target − It is a target function needed to execute. thisArg − It refers to the context whose elements should be accessed using this keyword in the function body. arguments − It is an array of arguments to pass to the function. Example In the below code, getDetails is a proxy object created for the getWatchDetails() function. The handler object contains the apply() method and calls the target function. We have called the getDetails() proxy by passing the watch object as a parameter. <html> <body> <p id = “output”> </p> <script> const watch = { brand: “Casio”, color: “Blue”, price: 2000, } const getWatchDetails = function (watch) { return `Brand: ${watch.brand}, Color: ${watch.color}, price: ${watch.price}`; } const getDetails = new Proxy(getWatchDetails, { apply(target, thisArg, args) { return target(…args).toUpperCase(); } }); document.getElementById(“output”).innerHTML += getDetails(watch); </script> </body> </html> Output BRAND: CASIO, COLOR: BLUE, PRICE: 2000 Uses of the Proxy Object

JavaScript – Destructuring Assignment

JavaScript – Destructuring Assignment ”; Previous Next Destructuring Assignment In JavaScript, the destructuring assignment is an expression that allows us to unpack the values from the arrays or objects and store them in individual variables. It is a technique to assign array values or object properties to the variables. The destructuring assignment syntax is introduced in ECMAScript 6 (ES6). Before ES6, developers were unpacking the object properties manually as shown in the example below. Array unpacking before ES6 In the example below, the ”arr” array contains the fruit names. After that, we created different variables and assigned array elements to the variables. <html> <body> <p id = “output”> </p> <script> const arr = [“Apple”, “Banana”, “Watermelon”]; const fruit1 = arr[0]; const fruit2 = arr[1]; const fruit3 = arr[2]; document.getElementById(“output”).innerHTML = “fruit1: ” + fruit1 + “<br>” + “fruit2: ” + fruit2 + “<br>” + “fruit3: ” + fruit3; </script> </body> </html> Output fruit1: Apple fruit2: Banana fruit3: Watermelon The above code will work if the array doesn”t contain the dynamic number of elements. What if the array contains 20+ elements? Will you write 20 lines of the code? Here the concept of the destructuring assignment comes into the picture. Array Destructuring Assignment You can follow the syntax below to use destructuring assignment to unpack array elements. const [var1, var2, var3] = arr; In the above syntax, ”arr” is an array. The var1, var2, and var3 are variables to store array elements. You can also similarly unpack the objects. Example The below example implements the same logic as the above example. Here, we have used the destructuring assignment to unpack the array elements. The code gives the same output as the previous example. <html> <body> <p id = “output”> </p> <script> const arr = [“Apple”, “Banana”, “Watermelon”]; const [fruit1, fruit2, fruit3] = arr; document.getElementById(“output”).innerHTML = “fruit1: ” + fruit1 + “<br>” + “fruit2: ” + fruit2 + “<br>” + “fruit3: ” + fruit3; </script> </body> </html> Output fruit1: Apple fruit2: Banana fruit3: Watermelon Example: Nested Array Destructuring In the example below, we created a nested array. To access these elements, we used nested array destructuring assignment. Try the following example – <html> <body> <p id = “output”> </p> <script> const arr = [“Apple”, [“Banana”, “Watermelon”]]; const [x, [y, z]] = arr; document.getElementById(“output”).innerHTML = x + “<br>” + y + “<br>” + z ; </script> </body> </html> Output Apple Banana Watermelon Object Destructuring Assignment You can follow the syntax below to use destructuring assignment to unpack object elements. const {prop1, prop2, prop3} = obj; In the above syntax, ”obj” is an object. The prop1, prop2, and prop3 are variables to store object properties. Example The below example implements the same logic as in the example of array destructuring assignment. Here, we have used the destructuring assignment to unpack the object elements. <html> <body> <div id = “output1”> </div> <div id = “output2”> </div> <script> const fruit = { name: “Apple”, price: 100, } const {name, price} = fruit; document.getElementById(“output1”).innerHTML = “fruit name: ” + name; document.getElementById(“output2”).innerHTML = “fruit price: ” + price; </script> </body> </html> Output fruit name: Apple fruit price: 100 Example: Nested Object Destructuring In the example below, we defined a nested object called person with two properties age and name. The name property contains two properties called fName and lName. We access these properties using nested destructuring. <html> <body> <div id = “output”> </div> <script> const person = { age: 26, name: { fName: “John”, lName: “Doe” } } // nested destructuring const {age, name: {fName, lName}} = person; document.getElementById(“output”).innerHTML = “Person name: ” + fName + ” ” + lName + “<br>”+ “Person age: ” + age; </script> </body> </html> Output Person name: John Doe Person age: 26 What”s Next? In the next chapters, we will learn the below concepts in detainls. Array destructuring − Unpacking the array elements. Object destructuring − Unpacking the object properties. Nested destructuring − Unpacking the nested array elements and nested objects. Print Page Previous Next Advertisements ”;

ECMAScript 2018

JavaScript – ECMAScript 2018 ”; Previous Next The ECMAScript 2018 version of JavaScript was released in 2018. ECMAScript 2017 introduced singnificant enhancement to the language. Two important features introduced in this version are asynchronous iteration for improved handling of asynchronous operations, and promise finally() to execute code regardless of promise resolution. This chapter will discuss all the new added features in ECMAScript 2018. New Added Features in ECMAScript 2018 Here are the new methods, features, etc., added to the ECMAScript 2018 version of JavaScript. Asynchronous iteration New features of the RegExp() Object Promise.finally() Rest object properties Here, we have explained each feature in detail. JavaScript Asynchronous Iteration You can also use the ”await” keyword with the for loop to make asynchronous iterations. For example, you are iterating multiple promises, and in each iteration, you need to stop the code execution until the current promise gets resolved or rejected. Example In the below code, we have defined the async generator function named gen_function. The gen_func() function makes 5 iterations using the loop. In each iteration, it awaits to resolve the promise and returns p. In the test() function, we used the ”await” keyword with the for loop to make asynchronous iterations. It updates the output after every 0.5 seconds. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(“demo”); // Generator function async function* gen_function() { for (let p = 0; p < 5; p++) { await new Promise(res => setTimeout(res, 500)); yield p; } } async function test() { for await (const ele of gen_function()) { output.innerHTML += “Returned element is: ” + ele + “<br>”; } } test(); </script> </body> </html> Output Returned element is: 0 Returned element is: 1 Returned element is: 2 Returned element is: 3 Returned element is: 4 New features of the RegExp() object In ECMAScript 2018, the following four new regular expression features were introduced − Unicode Property Escapes (p{…}) Lookbehind Assertions (?<= ) and (?<! ) Named Capture Groups s (dotAll) Flag Unicode Property Escapes (p{…}) The Unicode property escape allows you to escape the Unicode character. You need to represent the Unicode in the curly braces followed by the ”p”. Example In the below code, we use the regular expression to check whether the tet contains the letter using the Unicode property access. <html> <body> <div id = “output1″>regex.test(”Y”): </div> <div id = “output2″>regex.test(”6”): </div> <script> const regex = /p{Letter}/u; // To Match letters only document.getElementById(“output1″).innerHTML += regex.test(”Y”); // true document.getElementById(“output2″).innerHTML += regex.test(”6”); // false </script> </body> </html> Output regex.test(”Y”): true regex.test(”6”): false Lookbehind Assertions (?<= ) and (?<! ) The Lookbehind assertion allows you to find a particular subpattern followed by a particular sub patter. The positive look-behind assertion is equal to ?<=, and the negative look-behind assertion is ?<!. Example In the below code, we are looking for a word after the ”@” using the look behind the assertion. It finds words after the ”@” pattern. <html> <body> <div id = “output”>lookBeind.exec(”[email protected]”)[0]: </div> <script> const lookBeind = /(?<=@)w+/; document.getElementById(“output”).innerHTML += lookBeind.exec(”[email protected]”)[0]; // Prints domain </script> </body> </html> Output lookBeind.exec(”[email protected]”)[0]: tutorialspoint Named Capture Groups You can give a unique name to each group of the regular expression. The group names make it easy to extract the patterns from the string. Example In the code below, we have defined the regular expression to match the date pattern. Also, we have named the groups” year, month, and day. After that, we extracted the year from the date using the group name. <html> <body> <div id = “output”>The year of the date is: </div> <script> const datePattern = /(?<year>d{4})-(?<month>d{2})-(?<day>d{2})/; const match = datePattern.exec(”2023-08-22”); document.getElementById(“output”).innerHTML += match.groups.year; </script> </body </html> Output The year of the date is: 2023 s (dotAll) Flag The ”.” (dot) character matches any character except the new line in a regular expression. If you also want to match the new line using the ”.” Character, you need to use the ”/s” flag, as shown in the example below. Example In the below code, we have added the ”.” Character in the regular expression pattern to match any character, and also added s flag. In the output, you can see that ”.” character also matches with the ”n”. <html> <body> <div id = “output”>strRegex.test(”Hellonprogrammers”): </div> <script> const strRegex = /Hello.programmers/s; document.getElementById(“output”).innerHTML += strRegex.test(”Hellonprogrammers”); </script> </body> </html> Output strRegex.test(”Hellonprogrammers”): true JavaScript Promise finally() You can use the finally() block with promises to execute the particular code after the promise gets resolved or rejected. It is similar to the try…catch…finally block. Example In the example below, we created the promise and stored it in the getData variable. The promise gets resolved after 1000 milliseconds. After that, we use the ”then…finally”, block to execute the promise. In the output, you can observe that code of the ”finally” block always gets executed. <html> <body> <div id = “output”> </div> <script> const getData = new Promise((res, rej) => { setTimeout(() => { res(“Promise resolved!”); }, 1000); }); getData .then(result => { document.getElementById(“output”).innerHTML += result + “<br>”; }) .finally(() => { document.getElementById(“output”).innerHTML += “In the finally block!”; }); </script> </body> </html> Output Promise resolved! In the finally block! JavaScript Rest Object Properties You can use the spread operator while destructuring the objects. The spread operator allows you to collect the remaining properties in a single variable in the object format. Example In the example below, the numbers object contains 4 properties. While destructuring, we get the value of the num1 property and store other properties in the nums variable using the spread operator. <html> <body> <div id = “output”> </div> <script> const numbers = { num1: 40, num2: 50, num3: 80, num4: 90, } const { num1, …nums } = numbers; document.getElementById(“output”).innerHTML = “num1 = ” + num1 + “<br>” + “nums = ” + JSON.stringify(nums); </script> </body> </html> Output num1 = 40 nums = {“num2″:50,”num3″:80,”num4″:90} Print Page Previous Next Advertisements ”;

JavaScript – Web API

JavaScript – Web API ”; Previous Next A Web API is an application programming interface (API) for web. The concept of the Web API is not limited to JavaScript only. It can be used with any programming language. Let’s learn what web API is first. What is Web API? The API is an acronym for the Application Programming Interface. It is a standard protocol or set of rules to communicate between two software components or systems. A web API is an application programming interface for web. The API provides an easy syntax to use the complex code. For example, you can use the GeoLocation API to get the coordinates of the users with two lines of code. You don’t need to worry about how it works in the backend. Another real-time example you can take is of a power system at your home. When you plug the cable into the socket, you get electricity. You don’t need to worry about how electricity comes into the socket. There are different types of web APIs, some are as follow − Browser API (Client-Side JavaScript API) Server API Third Party APIs Let’s discuss each of the above type of web APIs in detail − Browser API (Client-side JavaScript API) The browser APIs are set of Web APIs that are provided by the browsers. The browser API is developed on top of the core JavaScript, which you can use to manipulate the web page”s functionality. There are multiple browser APIs available which can be used to interact with the web page. Following is a list of common browser APIs − Storage API − It allows you to store the data in the browser”s local storage. DOM API − It allows you to access DOM elements and manipulate them. History API − It allows you to get the browser’s history. Fetch API − It allows you to fetch data from web servers. Forms API − It allows you to validate the form data. Server API A server API provides different functionalities to the web server. Server APIs allow developers to interact with server and access data and resources. For example, REST API is a server API that allows us to create and consume the resources on the server. A JSON API is popular API for accessing data in JSON format. The XML API is a popular API for accessing data in XML format. Third-party APIs The third-party API allows you to get the data from their web servers. For example, YouTube API allows you to get the data from YouTube’s web server. Here is the list of common third-party APIs. YouTube API − It allows you to get YouTube videos and display them on the website. Facebook API − It allows you to get Facebook posts and display them on the website. Telegram API − It allows you to fetch and send messages to the telegram. Twitter API − It allows you to get tweets from Twitter. Pinterest API − It allows you to get Pinterest posts. You can also create and expose API endpoints for your own software. So, other applications can use your API endpoints to get the data from your web server. Fetch API: An Example of Web API Here is an example of how to use the fetch API. In the below example, we Fetch API to access data from a given URL (”https://jsonplaceholder.typicode.com/todos/5). The fetch() method returns a promise that we handle using the “then” block. First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page. <html> <body> <h3> Fetch API: An Example of Web API </h3> <div id = “output”> </div> <script> const URL = ”https://jsonplaceholder.typicode.com/todos/5”; fetch(URL) .then(res => res.json()) .then(data => { document.getElementById(”output”).innerHTML += “The data accessed from the API: ” + “<br>” + JSON.stringify(data); }); </script> </body> </html> JavaScript Web API List Here, we have listed the most common web APIs. API Description Console API It is used to interact with the browser’s console. Fetch API It is used to fetch data from web servers. FullScreen API It contains various methods to handle HTML elements in full-screen mode. GeoLocation API It contains the methods to get the user’s current location. History API It is used to navigate in the browser based on the browser’s history. MediaQueryList API It contains methods to query media. Storage API It is used to access the local and session storage. Forms API It is used to validate the form data. In upcoming chapters, we will cover the above APIs in details/> Print Page Previous Next Advertisements ”;

JavaScript – Mixins

JavaScript – Mixins ”; Previous Next Mixins in JavaScript The mixins in JavaScript allow you to add the properties of the other objects or classes to the target object”s or class”s prototype and extend the functionality of the target object. After that, you can access the other object”s method using the target object. In JavaScript, each object contains a built-in property called prototype. The prototype is itself an object. So prototype object will have its own prototype property making what we call prototype changing. Prototype chain helps to inherit properties and methods from other objects. Also, you can say that mixins allow you to borrow functionality from other objects or classes. In JavaScript, inheritance allows you to extend the functionality of the object or class. Similarly, Mixins also allows you to extend the functionality of the object or classes. JavaScript Mixins with Objects Using the concept of the JavaScript mixins, you can extend the functionality of the target object by adding properties and methods of the other objects. Syntax Following is the syntax to use Mixins with objects in JavaScript − Object.assign(target, obj); In the above syntax, we used the Object.assign() method to extend the functionality of the target object. Parameters target − It is an object whose functionality you need to extend. obj − It is an object whose functionality will be extended by the target object. Example In the below code, the parent object contains the printMessage(), and the child object contains the showName() method. Both methods print different messages. After that, we used the Object.assign() method to extend the functionality of the child object with the methods of the parent object. Next, we invoke the parent and child object message using the child object only, and you can observe the output. <html> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); const parent = { name: “parent”, printMessage() { output.innerHTML = ”This is a parent object.<br>”; } } const child = { showName() { output.innerHTML += ”This is a child object.<br>”; } } Object.assign(child, parent); // Mixins child.printMessage(); //Executing the method of parent object using child object child.showName(); </script> </body> </html> Output This is a parent object. This is a child object. JavaScript Mixins with Classes You can also extend the functionality of the classes through objects using the mixins. Syntax We can follow the syntax below to use mixins with classes − Object.assign(class_name.prototype, obj); In the above syntax, we have passed the prototype of the class as the first parameter and the object as a second parameter whose functionalities need to extend with classes. Example In the below code, the animal object contains the ”eats” property and run() method. The cat class contains only the constructor. We add the methods and properties of the animal object to the cat class”s prototype. After that, we execute the run() method using the instance of the cat class. <html> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); const animal = { eats: true, run() { output.innerHTML += “Animals run. <br>”; } } class cat { constructor() { this.name = “Cat”; } } Object.assign(cat.prototype, animal); // Mixins const catObj = new cat(); output.innerHTML += “Cat eats: ” + catObj.eats + “<br>”; catObj.run(); </script> </body> </html> Output Cat eats: true Animals run. Achieving Multiple Inheritance Using the Mixins JavaScript doesn”t support multiple inheritance, which means extending one class”s functionality with multiple classes or objects. So, you can achieve multiple inheritance using mixins. Syntax Users can follow the syntax below to use the mixins to achieve multiple inheritance. Object.assign(target, ob1, obj); The above syntax will add the obj1 and obj2 object”s functionality to the target object. Example: Inheriting multiple objects In the below code, eat object contains the eatFood() method, and the drink object contains the drinkWater() method. We add properties and methods of the eat and drink object to the person object. After that, we access the eatFood() and drinkWater() methods using the person object. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(“demo”); const eat = { eatFood() { output.innerHTML += “Person is eating the food! <br>”; } } const drink = { drinkWater() { output.innerHTML += “Person is drinking water! <br>”; } } const person = { name: “John”, } Object.assign(person, eat, drink); // Mutiple Mixins person.eatFood(); person.drinkWater(); </script> </body> </html> Output Person is eating the food! Person is drinking water! Example: Multiple Inheritance with Classes The below example demonstrates extending one class with multiple classes. The Entity class is the parent class, and it contains the state() method. The Human class extends the Entity class and contains the walk() method. The Driver() function creates a new class, extends a class passed as a parameter, and adds the Drive() method to the class. Similarly, the Swimmer() function creates a new class, extends the class with a class passed as a parameter, and adds the swim() method. After that, we defined multiple other classes. The person class extends the class returned by the Driver() class. The Driver() function returns a new class extended with the Human class. Same way, we have created the Mechanic and SwimmerPerson classes. After that, we have created the objects of various classes and executed the methods inherited by them. <html> <body> <p id = “demo”> </p> <script> let output = document.getElementById(“demo”); // Parent class class Entity { state() { return ”It is in the idle state!”; } } // Child class class Human extends Entity { walk() { return ”walking on the field.”; } } // Custom functionalities function Driver(parentClass) { return class extends parentClass { drive() { return ”driving on the road”; } }; } function Swimmer(parentClass) { return class extends parentClass { swim() { return ”swimming in water”; } }; } // Some other classes class Person extends Driver(Human) { } class Mechanic extends Driver(Entity) { } class SwimmerPerson extends Swimmer(Person) { } // Objects of classes const person = new Person(); const personDrive = person.drive(); const mechanic = new Mechanic();

JavaScript – Page Redirect

JavaScript – Page Redirection ”; Previous Next What is Page Redirection? You might have encountered a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection. This concept is different from JavaScript Page Refresh. There could be various reasons why you would like to redirect a user from the original page. We are listing down a few of the reasons − You did not like the name of your domain and you are moving to a new one. In such a scenario, you may want to direct all your visitors to the new site. Here you can maintain your old domain but put a single page with a page redirection such that all your old domain visitors can come to your new domain. You have built-up various pages based on browser versions or their names or may be based on different countries, then instead of using your server-side page redirection, you can use client-side page redirection to land your users on the appropriate page. The Search Engines may have already indexed your pages. But while moving to another domain, you would not like to lose your visitors coming through search engines. So you can use client-side page redirection. But keep in mind this should not be done to fool the search engine, it could lead your site to get banned. How Page Re-direction Works? The implementations of Page-Redirection are as follows. Example 1 It is quite simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows. <html> <head> <title>Page Redirection Example</title> </head> <body> <p>Click the following button, you will be redirected to home page.</p> <form> <input type=”button” value=”Redirect Me” onclick=”Redirect();” /> </form> <script type=”text/javascript”> function Redirect() { window.location = “https://www.tutorialspoint.com”; } </script> </body> </html> Example 2 You can show an appropriate message to your site visitors before redirecting them to a new page. This would need a bit time delay to load a new page. The following example shows how to implement the same. Here setTimeout() is a built-in JavaScript function which can be used to execute another function after a given time interval. <html> <head> <title>Page Redirection Example</title> </head> <body> <p>You will be redirected to main page in 10 sec.</p> <script> function redirect() { window.location = “https://www.tutorialspoint.com”; } setTimeout(”redirect()”, 10000); </script> </body> </html> Output You will be redirected to tutorialspoint.com main page in 10 seconds! Example 3 The following example shows how to redirect your site visitors onto a different page based on their browsers. <html> <head> <title>Browser Redirect</title> </head> <body> <script type = “text/javascript”> var browsername = navigator.appName; if( browsername == “Netscape” ) { window.location = “https://www.tutorialspoint.com/javascript/index.htm”; } else if ( browsername ==”Microsoft Internet Explorer”) { window.location = “https://www.tutorialspoint.com/articles/category/Javascript”; } else { window.location = “https://www.tutorialspoint.com/”; } </script> </body> </html> Print Page Previous Next Advertisements ”;