English 中文(简体)
ES8 - New Features
  • 时间:2024-12-22

ES8 - New Features


Previous Page Next Page  

This chapter focuses on the new features in ES8.

Padding a String

ES8 introduces two string handpng functions for padding a string. These functions can be used to add space or any desired set of characters to the beginning and end of a string value.

String. padStart()

This function pads the current string with a given input string repeatedly from the start, till the current string reaches the given length. The syntax of the padStart() function is given below −

Syntax


string_value.padStart(targetLength [, padString])

The padStart() function accepts two parameters which are as follows −

    targetLength − A numeric value that represents the target length of the string after padding. If the value of this parameter is lesser than or equal to the existing length of the string, the string value is returned as it is.

    padString − This is an optional parameter. This parameter specifies the characters that should be used to pad the string. The string value is padded with spaces if no value is passed to this parameter.

Example

The following example declares a string variable, product_cost. The variable will be padded with zeros from left until the total length of the string is seven. The example also illustrates behaviour of the padStart() function, if no value is passed to the second parameter.


<script>

   //pad the String with 0
   let product_cost =  1699 .padStart(7,0)
   console.log(product_cost)
   console.log(product_cost.length)

   //pad the String with blank spaces
   let product_cost1 =  1699 .padStart(7)
   console.log(product_cost1)
   console.log(product_cost1.length)
</script>

The output of the above code will be as stated below −


0001699
7
1699
7

String.padEnd()

This function pads the current string with a given input string repeatedly from the end, till the current string reaches the specified length.

The syntax of the padEnd() function is given below −

Syntax


string_value.padEnd(targetLength [, padString])

The padEnd() function accepts two parameters −

    targetLength − A numeric value that represents the target length of the string after padding. If the value of this parameter is lesser than or equal to the existing length of the string, the string value is returned as it is.

    padString − This is an optional parameter. This parameter specifies the characters that should be used to pad the string. The string value is padded with spaces if no value is passed to this parameter.

Example

The following example declares a string variable, product_cost. The variable will be padded with zeros from right until the total length of the string is seven. The example also illustrates behaviour of the padStart() function, if no value is passed to the second parameter.


<script>

   //pad the string with x
   let product_cost =  1699 .padEnd(7, x )
   console.log(product_cost)
   console.log(product_cost.length)
   
   //pad the string with spaces
   let product_cost1 =  1699 .padEnd(7)
   console.log(product_cost1)
   console.log(product_cost1.length)
</script>

The output of the above code will be as mentioned below −


1699xxx
7
1699
7

Traipng Commas

A traipng comma is simply a comma after the last item in a pst. Traipng commas are also known as final commas.

Traipng Commas and Array

Traipng commas in arrays are skipped while using Array.prototype.forEach loop.

Example

The following example iterating an array with traipng commas using foreach loop.


<script>

   let marks = [100,90,80,,]
   console.log(marks.length)
   console.log(marks)
   marks.forEach(function(e){ //ignores empty value in array
      console.log(e)
   })
</script>

The output of the above code will be as shown below −


4
[100, 90, 80, empty]
100
90
80

Traipng commas and function call

Traipng commas, passed as arguments, when defining or invoking a function are ignored by JavaScript runtime engine. However, there are two exceptions −

    Function definitions or invocation that contains only a comma will result in SyntaxError. For example, the following snippet will throw an error −


function test(,){} // SyntaxError: missing formal parameter
(,)=>{}; //SyntaxError: expected expression, got  , 
test(,) //SyntaxError: expected expression, got  , 

    Traipng commas cannot be used with rest parameters.


function test(...arg1,){} // SyntaxError: parameter after rest parameter
(...arg1,)=>{} // SyntaxError: expected closing parenthesis, got  , 

Example

The following example declares a function with traipng commas in the argument pst.


<script>

   function sumOfMarks(marks,){ // traipng commas are ignored
      let sum=0;
      marks.forEach(function(e){
         sum+=e;
      })
      return sum;
   }

   console.log(sumOfMarks([10,20,30]))
   console.log(sumOfMarks([1,2,3],))// traipng comma is ignored
</script>

The output of the above code is as follows −


60
6

Object:entries() and values()

ES8 introduces the following new methods to the built-in Object type −

    Object.entries − The Object.entries() method can be used to access all the properties of an object.

    Object.values() − The Object.values() method can be used to access values of all properties of an object.

    Object.getOwnPropertyDescriptors() − This method returns an object containing all own property descriptors of an object. An empty object may be returned if the object doesn t have any properties.

Example


<script>
   const student ={
      firstName: Kannan ,
      lastName: Sudhakaran 
   }
   console.log(Object.entries(student))
   console.log(Object.values(student))
</script>

The output of the above code will be as follows −


[
["firstName", "Kannan"],
["lastName", "Sudhakaran"],
]
["Kannan", "Sudhakaran"]

Example


<script>
   const marks = [10,20,30,40]
   console.log(Object.entries(marks))
   console.log(Object.values(marks))
</script>

The output of the above code will be as given below −


["0", 10],
["1", 20],
["2", 30],
["3", 40]
]
[10, 20, 30, 40]

Example


<script>
   const student = {
      firstName :  Mohtashim ,
      lastName:  Mohammad ,
      get fullName(){
         return this.firstName +  : + this.lastName
      }
   }
   console.log(Object.getOwnPropertyDescriptors(student))
</script>

The output of the above code will be as mentioned below −


{firstName: {value: "Mohtashim", writable: true, enumerable: true, configurable: true}
fullName: {get: ƒ, set: undefined, enumerable: true, configurable: true}
lastName: {value: "Mohammad", writable: true, enumerable: true, configurable: true}
}

Async and Await

Async/Await is a very important feature in ES8.It is a syntactic sugar for Promises in JavaScript. The await keyword is used with promises. This keyword can be used to pause the execution of a function till a promise is settled. The await keyword returns value of the promise if the promise is resolved while it throws an error if the promise is rejected. The await function can only be used inside functions marked as async. A function that is declared using the async keyword always returns a promise.

Syntax

The syntax of async function with await is given below −


async function function_name(){
   let result_of_functionCall = await longRunningMethod();
}
//invoking async function

function_name().then(()=>{})
   .catch(()=>{})

Consider an example that has an asynchronous function that takes two seconds to execute and returns a string value. The function can be invoked in two ways as shown below

    Using promise.then()

    Using aync/await.

The below code shows invoking the asynchronous function using the traditional ES6 syntax - promise.then()


<script>
   function fnTimeConsumingWork(){
      return new Promise((resolve,reject)=>{
         setTimeout(() => {
            resolve( response is:2 seconds have passed )
         }, 2000);
      })
   }

   fnTimeConsumingWork().then(resp=>{
      console.log(resp)
   })
   console.log( end of script )
</script>

The output of the above code will be as follows −


end of script
response is:2 seconds have passed

The below code shows a cleaner way of invoking the asynchronous function using ES8 syntax - async/await


<script>
   function fnTimeConsumingWork(){
      return new Promise((resolve,reject)=>{
         setTimeout(() => {
            resolve( response is:2 seconds have passed )
         }, 2000);
      })
   }
   async function my_AsyncFunc(){
      console.log( inside my_AsyncFunc )
      const response = await fnTimeConsumingWork();// clean and readable
      console.log(response)
   }
   my_AsyncFunc();
   console.log("end of script")
</script>

The output of the above code will be as mentioned below −


inside my_AsyncFunc
end of script
response is:2 seconds have passed

Promise chaining with Async/await

The following example implements promise chaining using the async/await syntax.

In this example, add_positivenos_async() function adds two numbers asynchronously and rejects if negative values are passed. The result from the current asynchronous function call is passed as parameter to the subsequent function calls.


<script>
   function add_positivenos_async(n1, n2) {
      let p = new Promise(function (resolve, reject) {
         if (n1 >= 0 && n2 >= 0) {
            //do some complex time consuming work
            resolve(n1 + n2)
         } else
            reject( NOT_Postive_Number_Passed )
      })
      return p;
   }
   async function addInSequence() {
      let r1 = await add_positivenos_async(10, 20)
      console.log("first result", r1);
      let r2 = await add_positivenos_async(r1, r1);
      console.log("second result", r2)
      let r3 = await add_positivenos_async(r2, r2);
      console.log("third result", r3)
      return "Done Sequence"
   }
   addInSequence().then((r)=>console.log("Async :",r));
   console.log( end )
</script>

The output of the above code will be as given below−


end
first result 30
second result 60
third result 120
Async : Done Sequence
Advertisements