Author: Saim Khalid

  • Asynchronous JavaScript

    Asynchronous JavaScript is a programming technique that enables your program to start a potentially long-running task and continue to executing other tasks parallelly. JavaScript is a single-threaded programming language. It means you can execute a single script or particular code at a time. JavaScript control flow moves the line by line and executes each line of code.

    We can implement asynchronous operations in our JavaScript programs using callback functions, promises, async/await etc. The callback functions are functions passed as arguments to other functions. The promises are objects representing the success of failure of an asynchronous operation. The async/await syntax is simple implementation of promises. We will discuss these approaches in details in respective chapters.

    To perform the multiple tasks parallelly, you need asynchronous JavaScript.

    Lets understand what synchronous JavaScript is before understanding asynchronous JavaScript.

    What is Synchronous JavaScript?

    The Synchronous JavaScript executes the JavaScript code line-by-line. The control flow moves from top to bottom and runs each statement one by one.

    Lets understand it via the example below.

    Example

    The control flow for the code is given below.

    • It calls the test1() function.
    • In the test1() function, it prints the start message.
    • Next, it calls the test2() function.
    • The test2() function prints the start and end messages.
    • After that, it prints the end message in the test1() function.
    • End of the code execution.
    <html><body><div id ="demo"></div><script>let output = document.getElementById('demo');functiontest2(){
    
         output.innerHTML +='&lt;br&gt;test2 started!';
         output.innerHTML +='&lt;br&gt;test2 finished!';}functiontest1(){
         output.innerHTML +='test1 started!';test2();
         output.innerHTML +='&lt;br&gt;test1 finished!';}test1();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    test1 started!
    test2 started!
    test2 finished!
    test1 finished!
    

    It creates a call stack, adds the code to it, and executes the code in the last in, first out (LIFO) order.

    Now, lets understand that what is the asynchronous JavaScript.

    What is Asynchronous JavaScript?

    Asynchronous JavaScript enables simultaneous code execution. You can use asynchronous JavaScript to make your application multi-threaded. It allows you to perform time-consuming or expensive tasks together.

    Lets understand the Asynchronous JavaScript via the example below.

    Example

    The execution flow of the code is explained below.

    • It prints the start message.
    • After that, it prints the end message without waiting until the execution of the setTimeOut() method is finished.
    • At last, it executes the code of the setTimeOut() method.
    <html><body><div id ="demo"></div><script>let output = document.getElementById('demo');
    
      output.innerHTML +="Code execution started. &lt;br&gt;";setTimeout(function(){
         output.innerHTML +="setTimeout() called. &lt;br&gt;";},1000);
      output.innerHTML +="Code execution finished. &lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Code execution started.
    Code execution finished.
    setTimeout() called.
    

    By writing the asynchronous JavaScript code, you can execute another JavaScript code without waiting to finish the execution of the particular code.

    Why Do We Need Asynchronous JavaScript?

    In the above section, we have learned to write the asynchronous JavaScript code via simple example. But the question is when you need to write the asynchronous JavaScript code as you dont need to perform simple tasks like printing the messages.

    Lets understand it via the example below.

    Example

    In the below code, we find the first 10 lakh prime numbers. For that, we traverse through numbers and check whether the number is prime using the checkForPrime() function.

    In the code, you can click the generate prime button. The code will start finding the first 10 lakh prime numbers. After that, you can immediately click the print message button to print the message. You can observe that the web page is responsive and does not print any message.

    However, it will print the message once the execution of the getPrimes() function is finished.

    So, it is necessary to complete such time-expensive tasks parallelly. Otherwise, it makes the web page unresponsive.

    <html><body><button onclick ="getPrimes()"> Generate primes </button><button onclick ="printMessage()"> Print Message </button><div id ="demo"></div><script>let output = document.getElementById('demo');// Function to check whether the number is a prime numberfunctioncheckForPrime(num){for(let p =2; p <= Math.sqrt(num); p++){if(num % p ===0){// Check whether the number is divisible by preturnfalse;}}return num >1;}functiongetPrimes(){const primeNums =[];// Array to store prime numberslet p =1;while(primeNums.length <1000000){// Find first 10 lakh prime numbersif(checkForPrime(p)){
    
               primeNums.push(p);}
            p++;}
         output.innerHTML +="The execution of the getPrime() function is completed. &lt;br&gt;";}functionprintMessage(){// Function to print the message
         output.innerHTML +="Button is clicked! &lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Asynchronous JavaScript

    Real-time Use Cases of Asynchronous JavaScript

    Here are the real-time use cases of asynchronous JavaScript.

    Fetching data from API

    When you fetch data from the API, it takes time to get the data according to the server's response time. So, you can use the asynchronous JavaScript to continue the execution of the other code without waiting for the API response.

    Loading external resources

    Sometimes, it happens that you need to load multiple libraries, external scripts, images, etc., into the application. The web page doesnt allow you to interact with the web page without loading all external resources. So you can load the external resources asynchronously.

    Task scheduling

    You can use asynchronous JavaScript to schedule the tasks using the setTimeOut() method or perform tasks after a particular interval using the setInterval() method.

    Data validation

    Sometimes, developers are required to do data validation. You can perform such tasks in the background or parallel with other codes.

    File uploads

    If you allow users to upload large files, it may take time to upload according to users' internet speed. So you can execute the file uploading asynchronously.

    Data caching

    The data caching is one of the most important features of the application to increase the performance and may take time according to the data size. So, you can use the promises to cache the data asynchronously.

  • ECMAScript 2022

    The ECMAScript 2022 standard was released in 2022. Important features added to this update include private methods and fieldsArray at() and String at() methods etc. This chapter discuss all the newly added features in ECMAScript 2022.

    New Features Added in ECMAScript 2022

    Here are the new methods, features, etc., added to the ECMAScript 2022 version of JavaScript.

    • Array at() Method
    • String at() Method
    • Private methods and fields
    • Object.hasOwn()
    • error.cause
    • await import

    Here, we have explained each feature in detail.

    Array at() Method

    ECMAScript 2022 (ES2022) introduced Array at() method to arrays. In JavaScript, array at() method used to access the array element from the particular index. You can’t use the negative index in the arr[index] representation, but with the array.at() method, you can also use the negative index to access array elements.

    When you use the negative index, it returns the array from the last.

    Example

    In the below code, we access the last and third-last elements from the array using the negative indexes and array.at() method.

    <body><div id ="demo1">The last array element is:</div><div id ="demo2">The third last array element is:</div><script>const arr =[10,20,60,72,6,12,23];
    
      document.getElementById("demo1").innerHTML += arr.at(-1);
      document.getElementById("demo2").innerHTML += arr.at(-3);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The last array element is: 23
    The third last array element is: 6
    

    String at() Method

    ECMAScript introduced String at() method to strings. In JavaScript, the String at() method is used to access the characters from the particular string index. It also accepts the negative index as an argument.

    Example

    In the code below, we access the last and fourth last characters from the string using the negative indexes and string.at() method.

    <html><body><div id ="demo1">The last string character is:</div><div id ="demo2">The fourth last string character is:</div><script>let str ="Hello world";
    
      document.getElementById("demo1").innerHTML += str.at(-1);
      document.getElementById("demo2").innerHTML += str.at(-4);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The last string character is: d
    The fourth last string character is: o
    

    Private Methods and Fields

    ECMAScript 2022 introduced the way to write private methods and fields. In JavaScritp, you can write the field name or method name followed by the hash sign ('#') to make them private. You can't access the private fields and methods using the class instance. However, you can access them inside the class.

    Example

    In the below code, the car class contains the 'brand' private field and the 'carBrand' private method. The getBrand() method is public.

    We have created the instance of the car class and invoked the getBrand() method using it. The getBrand() method calls the carBrand() method.

    <html><body><div id ="output"></div><script>classcar{
    
         #brand;constructor(brand){this.#brand = brand;}getBrand(){returnthis.#carBrand();}#carBrand(){return"The car brand is "+this.#brand;}}constBMW=newcar("BMW");
      document.getElementById("output").innerHTML =BMW.getBrand();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The car brand is BMW
    

    Object hasOwn() Method

    The Object.hasOwn() method is a replacement for the Object.hasOwnProperty() method. It is used to check whether the object contains a particular property.

    Example

    In the code below, we use the hasOwn() method to check whether the obj object contains the name property.

    <html><body><div id ="output"></div><script>const obj ={
    
         name:"sam",
         age:50,}
      document.getElementById("output").innerHTML ="Does obj contain name property? "+ obj.hasOwnProperty("name");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Does obj contain name property? true
    

    The error.cause Property

    The 'cause' is a property of the JavaScript object. It represents the reason for the error. It is introduced in ECMAScript 2022.

    Example

    In the below code, we throw a new error from the 'try' block. Also, we specify the reason for the error using the cause property.

    We access the 'cause' property value in the catch block to know the reason.

    <html><body><div id ="demo"></div><script>let output = document.getElementById("demo");try{
    
         output.innerHTML +="Inside the try block &lt;br&gt;";thrownewError("New error",{ cause:"Testing with error."})}catch(error){
         output.innerHTML +="The reason for the error is: "+ error.cause +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Inside the try block
    The reason for the error is: Testing with error.
    

    The Await Import

    You can use the asynchronous import to import the dynamic modules. You need to use the 'await' keyword for the asynchronous import.

    For example, the below code contains the self-invoking asynchronous function. Also, the 'await' keyword is used inside the function to await the import.

    (asyncfunction(){await(awaitimport('./math.js')).default();await(awaitimport('./operations.js')).default();})();

    Warning Some of the above features are not supported by some browsers. So, you can use the polyfill to avoid errors.

  • ECMAScript 2021

    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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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 =newPromise((res, rej)=>res());const promise2 =newPromise((res, rej)=>rej());const promises =[promise1, promise2];
    
    
      Promise.any(promises).then(()=&gt;{
            output.innerHTML +='One or more promises are resolved!';}).catch((err)=&gt;{
            output.innerHTML +='All promises are rejected:'+ err;});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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 &amp;&amp;="Hi";
      document.getElementById("output").innerHTML += str;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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.

  • ECMAScript 2020

    The ECMAScript 2020 version of JavaScript was released in 2020. Notable features added in this version include the nullish coalescing operator (??) for more concise default value assignment and dynamic import() for on-demand module loading. BigInt provides a way to safely work with very large integers. This chapter will discuss all the newly added features in ECMAScript 2020.

    Features Added in ECMAScript 2020

    Here are the new methods, features, etc., added to the ECMAScript 2020 version of JavaScript.

    • BigInt
    • Promise allSettled()
    • String matchAll()
    • The Nullish Coalescing Operator (??)
    • The Optional Chaining Operator (?.)

    Here, we have explained each feature in detail.

    BigInt Primitive DataType

    The ECMAScript 2020 introduced BigInt to the primitive data types. You can use the Big Int when you need to store a large number, which cant be represented using the 64-bit representation.

    To convert the number into the Big int, you can write the number followed by n.

    Example

    In the below code, we have defined the number of big int data type.

    <html><body><div id ="output">The number of bigint type is:</div><script>const bigNum =1325461651565143545565n;
    
      document.getElementById("output").innerHTML += bigNum;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The number of bigint type is: 1325461651565143545565
    

    The Nullish Coalescing Operator (??)

    The JavaScript Nullish Coalescing operator returns the left operand if it is not undefined or null. Otherwise, it returns the right operand. It is used to set default values to the variables.

    Example

    In the below code, the left operand for the nullish coalescing operator is undefined. So, it returns the value of the right operand.

    <html><body><div id ="output">The value of the str is:</div><script>let str =undefined??"Hello";
    
      document.getElementById("output").innerHTML += str;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of the str is: Hello
    

    Promise allSettled() Method

    The Promise.allSettled() method returns the status of all promises once all promises get fulfilled.

    Example

    In the code below, we have defined the array of promises.

    After that, we used the promise.allSettled() method to fulfill all promises. In the output, you can see that method returns the array of objects, representing the status and result of each promise.

    <html><body><div id ="output"></div><script>const promises =[
    
         Promise.resolve("Hello"),
         Promise.reject("Error message"),
         Promise.resolve(21342)];
      Promise.allSettled(promises).then(results=&gt;{
            document.getElementById("output").innerHTML +=JSON.stringify(results);});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    [{"status":"fulfilled","value":"Hello"},{"status":"rejected","reason":"Error message"},{"status":"fulfilled","value":21342}]
    

    The String matchAll() Method

    The string matchAll() method matches all occurrences of the particular string substring. It takes the string or regular expression as a parameter.

    Example

    In the below code, we used the String.matchAll() method to match the abcd substring in the str string. The method returns an iterator of all matching occurrences.

    <html><body><div id ="output">The matching results are:<br></div><script>let str ="Abcd abcd abcd";let matches = str.matchAll('abcd');for(let x of matches){
    
         document.getElementById("output").innerHTML += x +"&lt;br&gt;"}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The matching results are:
    abcd
    abcd
    

    The Optional Chaining Operator (?.)

    The Optional chaining operator is used to access the nested object properties. If any nested object is undefined, it returns undefined rather than throwing an error.

    Example

    In the code below, the obj object contians the obj1 nested object, containing the name property.

    We try to access the obj2 objects name property with an optional chaining operator. Obj2 is not defined here, so it returns the undefined rather than throwing an error.

    <html><body><div id ="output">The name of obj2 is:</div><script>let obj ={
    
         obj1:{
            name:"JavaScript",}}
      document.getElementById("output").innerHTML += obj?.obj2?.name;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The name of obj2 is: undefined
    

    Warning Some of the above features are not supported by some browsers. So, you can use the polyfill to avoid errors.

  • ECMAScript 2019

    The ECMAScript 2019 standard was released in 2019. Important additions to this update include Array flat() and Array flatMap(), offering concise array manipulation methods. The Object.fromEntries() method simplifies object creation from key-value pairs. These improvements in ECMAScript 2019 aimed to enhance code conciseness and functionality. This chapter will discuss all the newly added features in ECMAScript 2019.

    New Features Added in ECMAScript 2019

    Here are the new methods, features, etc., added to the ECMAScript 2019 version of JavaScript.

    • Array.flat()
    • Array.flatMap()
    • Revised Array.Sort()
    • Object.fromEntries()
    • Optional catch binding
    • Revised JSON.stringify()
    • Revised Function.toString()
    • Separator symbols allowed in string literals
    • String.trimEnd()
    • String.trimStart()

    JavaScript Array flat() Method

    The ECMAScript 2019 introduced Array.flat to the arrays. The JavaScript array flat() method is used to flatten the array by removing the nested array and adding its elements to the original array.

    Example

    In the code below, we used the array.flat() method to flatten the arr array.

    <html><body><div id ="output">The flatten array is:</div><script>const arr =[1,[10,20],30,[40,[50],60],70];
    
      document.getElementById("output").innerHTML +=  arr.flat();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The flatten array is: 1,10,20,30,40,50,60,70
    

    JavaScript Array flatMap()

    The ECMAScript 2019 also introduced Array flatMap to arrays. The array flatMap() flatten the array after mapping the array elements with new elements.

    Example

    In the below code, we return the array of two elements from the callback function of the flatMap() method. After that, the flatMap() method flattens it.

    In the output, you can see that 'updated' is a single array. So, it first maps the current element to a new element or array and flattens it.

    <html><body><div id ="output">The updated array is:</div><script>const arr =[2,4,6,8];const updated = arr.flatMap((ele)=>[ele *2, ele *3]);
    
      document.getElementById("output").innerHTML += updated;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The updated array is: 4,6,8,12,12,18,16,24
    

    Revised Array sort()

    In ECMAScript 2019, JavaScript array.prototype.sort() method has been revised to make it stable.

    Before 2019, the behavior of the sort() method was not consistent in sorting the equal elements. It could not preserve the original order for the same array elements.

    Now, array.sort() method is stable as it uses the variation of the merge sort.

    Example

    In the below code, we have defined the watches array containing multiple objects. Each object of the array contains the brand and price property.

    We used the sort() method to sort the array based on the value of the brand property. In the output, you can see that it preserves the original order for the same brand name.

    <html><body><div id ="output">The sorted array elements are:<br></div><script>const watches =[{ brand:"Titan", price:1000},{ brand:"Casio", price:1000},{ brand:"Titan", price:2000},{ brand:"Titan", price:3000}]
    
      watches.sort((a, b)=&gt; a.brand.localeCompare(b.brand))for(let obj of watches){
         document.getElementById("output").innerHTML +=JSON.stringify(obj)+"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The sorted array elements are:
    {"brand":"Casio","price":1000}
    {"brand":"Titan","price":1000}
    {"brand":"Titan","price":2000}
    {"brand":"Titan","price":3000}
    

    JavaScript Object fromEntries

    The Object fromEnteries() method allows you to create a new object from the 2-dimensional array. Each element of the array should be an array of length 2, containing the key-value pair for the object.

    Example

    In the below code, we have defined the 2D array containing the fruit name and price. After that, we used the Object.fromEntries() method to create an object from the array.

    <html><body><div id ="output">The fruits object is :</div><script>const entries =[["Apple",20],["Banana",40],["watermelon",30]];const fruits = Object.fromEntries(entries);
    
       
      document.getElementById("output").innerHTML +=JSON.stringify(fruits);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The fruits object is : {"Apple":20,"Banana":40,"watermelon":30}
    

    Optional catch binding

    After ECMAScript 2019, you can remove the 'catch' block parameter if you don't need it.

    For example, before ECMAScript 2019, you must need the parameters with the catch block.

    try{}catch(error){}

    After ECMAScript 2019,

    try{}catch{}

    Revised JSON.stringify()

    Before ECMAScript 2019, JavaScript JSON.stringify() method was not able to convert the Unicode characters into a string, but after ES10, it is possible, as shown in the example below.

    Example

    In the code below, we convert the Unicode character into the JSON string and then use the JSON.parse() method to parse the string.

    <html><body><div id ="output1">The unicode string value is:</div><div id ="output2">The unicode JSON value is:</div><script>let str =JSON.stringify("\u27A6");
    
      document.getElementById("output1").innerHTML += str;
      document.getElementById("output2").innerHTML +=JSON.parse(str);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The unicode string value is: ""
    The unicode JSON value is: 
    

    Revised Function toString()

    Before ECMAScript 2019, when you used the toString() method with the function, it returned the function's source code without comment, syntax, etc.

    After ES10, it returns the function with spaces, syntax, comments, etc.

    Example

    The toString() method returns the function after converting into the string in the below code. The resultant string contains the spaces, comments, etc.

    <html><body><div id ="output">After converting the function to string is:</div><script>functiontest(){return10*20;}
    
      document.getElementById("output").innerHTML += test.toString();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    After converting the function to string is: function test() { return 10 * 20; }
    

    Separator symbols allowed in string literals

    After ECMAScript 2019, you can use the separator symbols \u2028 and \u2029)to separate the line and paragraph in the string.

    Example

    In the below code, we used the Unicode character to separate the line. However, you won't be able to see separating lines directly as we use the innerHTML property to update the HTML.

    <html><body><div id ="output">The string with seprator symbol is:</div><script>let str ="Hi\u2028";
    
      document.getElementById("output").innerHTML += str;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript String trimEnd()

    The string trim() method was introduced in ECMAScript 2019. It is used to remove the whitespace from both ends of the string.

    The string.trimEnd() method removes the whitespaces from the end of the string.

    Example

    The code below removes the white spaces from the end of the string.

    <html><body><div id ="output">After removing white spaces from the end of the string:</div><script>let str ="   Hello World! ";
    
      document.getElementById("output").innerHTML += str.trimEnd();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    After removing white spaces from the end of the string: Hello World!
    

    JavaScript String trimStart()

    ECMAScript 2019 introdued the string trimStart() method. It removes the whitespaces from the start of the string.

    Example

    The code below removes the white spaces from the start of the string.

    <html><body><div id ="output">After removing white spaces from the start of the string:<br></div><script>let str ="   Hello World! ";
    
      document.getElementById("output").innerHTML += str.trimStart();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    After removing white spaces from the start of the string:
    Hello World!
  • ECMAScript 2018

    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 functionasyncfunction*gen_function(){for(let p =0; p <5; p++){awaitnewPromise(res=>setTimeout(res,500));yield p;}}asyncfunctiontest(){forawait(const ele ofgen_function()){
    
            output.innerHTML +="Returned element is: "+ ele +"&lt;br&gt;";}}test();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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;&lt;/script&gt;&lt;/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('Hello\nprogrammers'):</div><script>const strRegex =/Hello.programmers/s;
    
      document.getElementById("output").innerHTML += 
    strRegex.test('Hello\nprogrammers');</script></body></html>

    Output

    strRegex.test('Hello\nprogrammers'): 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 =newPromise((res, rej)=>{setTimeout(()=>{res("Promise resolved!");},1000);});
    
      getData
         .then(result=&gt;{
            document.getElementById("output").innerHTML += result +"&lt;br&gt;";}).finally(()=&gt;{
            document.getElementById("output").innerHTML +="In the finally block!";});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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 +"&lt;br&gt;"+"nums = "+JSON.stringify(nums);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    num1 = 40
    nums = {"num2":50,"num3":80,"num4":90}

  • ECMAScript 2017

    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 startlet end_updated = base.padEnd(18,"*");// Padding at the end
    
      document.getElementById("output1").innerHTML += start_updated;
      document.getElementById("output2").innerHTML += end_updated;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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 +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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:"15x12",
         paintBrand:"Asiant paints"}
      document.getElementById("output").innerHTML +=" "+ Object.values(wall);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Object values are: blue,15x12,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>asyncfunctionprintMessage(){let getData =newPromise(function(res, rej){setTimeout(()=>{res("Promise resolved !!");},500);});
    
         document.getElementById("output").innerHTML =await getData;}printMessage();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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));&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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.

  • ECMAScript 2016

    The ECMAScript 2016 version of JavaScript was released in 2016. Previously the old versions of JavaScript are named by numbers for example ES5 and ES6. Since 2016 the versions are named by the year they are released for example ECMAScript 2016, ECMAScript 17, etc. Lets discuss the featues added in ECMAScript 2016.

    New Features Added in ECMAScript 2016

    Here are the new methods, features, etc., added to the ECMAScript 2016 version of JavaScript.

    • Array includes() method
    • Exponentiation Operator (**)
    • Exponentiation Assignment Operator (**=)

    Here, we have explained each feature in detail.

    JavaScript Array includes() Method

    The JavaScript array includes() methods is used to check whether the array contains a particular element.

    Syntax

    The syntax of Array includes() method in JavaScript is as follows −

    arr.include(searchElement, fromIndex);

    Here arr is the original array, the searchElement is to be search from. The fromIndex is an optional argument if passed, the searching will start from the fromIndex index.

    Example

    In the below code, we use the array includes() method to check whether the watches array contains the ‘Noise’ brand.

    <html><body><div id ="output">Does watches array include Noise?</div><script>const watches =["Titan","Rolex","Noise","Fastrack","Casio"];
    
      document.getElementById("output").innerHTML += watches.includes("Noise");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Does watches array include Noise? true
    

    Example

    In the below code, we use the array includes() method to check whether the subjects array contains the 'Python' subject searching from index 1.

    <html><body><div id ="output">Does subjects array include Python fromIndex 1?</div><script>const subjects =["Java","JavaScript","Python","C","C++"];
    
      document.getElementById("output").innerHTML += subjects.includes("Python",1);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Does subjects array include Python fromIndex 1? true
    

    JavaScript Exponentiation Operator

    The JavaScript exponentiation operator is used to find the power of the first operand raised to the second operand.

    Syntax

    The syntax of expponentiation operator is as follow −

    x ** y;

    It returns the result of raising the first operand (x) to the power of the second operand (y).

    Example

    In the below code, we find the 22 using the exponentiation operator and store the resultant value in the 'res' variable.

    <html><body><div id ="output">The resultant value for2**2 is:</div><script>
    
      document.getElementById("output").innerHTML +=2**2;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The resultant value for 2 ** 2 is: 4
    

    Exponentiation Assignment Operator

    The JavaScript exponentiation assignment operator raises the power of the first operand by the second operand and assigns it to the first operand.

    Syntax

    The syntax of exponentiation assignment operator is as follows −

    x **= y;

    It assigns the result of raising the first operand (x) to the power of the second operand (y) to x.

    Example

    In the below code, we find the 102 and assign the resultant value to the 'num' variable using the exponentiation assignment operator.

    <html><body><div id ="output">The resultant value for10**2 is:</div><script>let num =10;
    
      num **=2;// exponentiation assignment operation
      document.getElementById("output").innerHTML += num;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The resultant value for 10 ** 2 is: 100

  • ES5

    The ES6 version of JavaScript was released in 2015, marking the second major revision of JavaScript. The ES6 is also known as ECMAScript 2015. Some of the important features introduced in ES6 are arrow functions, let and const keywords, Classes, res parameters, etc. This chapter will discuss all the newly added features in ES6 version.

    New Added Features in ES6

    Here are the new methods, features, etc., added to the ES6 version of JavaScript.

    • Arrow Functions
    • Array find()
    • Array findIndex()
    • Array from()
    • Array keys()
    • Classes
    • const keyword
    • Default Parameters
    • For/of
    • Function Rest Parameter
    • JavaScript Modules
    • let keyword
    • Map Objects
    • New Global Methods
    • New Math Methods
    • New Number Methods
    • New Number Properties
    • Promises
    • Set Objects
    • String.endsWith()
    • String.includes()
    • String.startsWith()
    • Symbol
    • The spread Operator

    Here, we have explained each feature in detail with examples.

    JavaScript Arrow Functions

    The arrow function is a way to write the shorter function code. The concept of the arrow functions allows you to define the function without using the function keyword, curly braces, and return keyword.

    Example

    In the below code, func() is a regular function, and the variable subtracts stores the arrow function.

    <html><body><div id ="output">The subtraction of20 and 10 is:</div><script>/* Normal function
    
      function func(a, b) {
         return a - b;
      }
      */// Arrow functionconstsubtract=(a, b)=&gt; a - b;      
      document.getElementById("output").innerHTML +=subtract(20,10);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The subtraction of 20 and 10 is: 10
    

    JavaScript Array find() Method

    The JavaScript array.find() method returns the first element that follows the particular condition.

    Example

    In the below code, we find the first array element whose length is less than 4 using the array.find() method.

    <html><body><div id ="output">The first array element whose length is less than 4 is:</div><script>const strs =["Hello","World","How","are","You"];functionfunc_len(value, index, array){return value.length <4;}
    
        
      document.getElementById("output").innerHTML += strs.find(func_len);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The first array element whose length is less than 4 is: How
    

    JavaScript Array findIndex()

    The JavaScript array.findIndex() method is similar to the array.find() method, but it returns the index of the first element that matches the particular condition. It returns the 0-based index.

    Example

    In the below code, we find the index of the first element whose length is less than 4 using the array.findIndex() method.

    <html><body><div id ="output">The first array element whose length is less than 4 is:</div><script>const strs =["Hello","World","How","are","You"];functionfunc_len(value, index, array){return value.length <4;}
    
        
      document.getElementById("output").innerHTML += strs.findIndex(func_len);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The first array element whose length is less than 4 is: 2
    

    JavaScriipt Array from()

    The JavaScript Array.from() method creates an array from the iterable passed as an argument.

    Example

    In the below code, we create an array from the string using the Array.from() method. However, you can also pass iterable as an argument of the Array.from() method.

    <html><body><div id ="output">The array from the Hello string is:</div><script>
    
      document.getElementById("output").innerHTML += Array.from("Hello");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The array from the Hello string is: H,e,l,l,o
    

    JavaScript Array keys()

    The JavaScript array.keys() method returns an iterator to iterate the keys. The keys of the array element are indexes of the array elements.

    Example

    In the below code, we use the keys() method to get the iterators of keys of the nums[] array. After that, we use the for/of loop to traverse the keys of the array.

    <html><body><div id ="demo">The keys of the nums array is:<br></div><script>const output = document.getElementById("demo");const nums =[45,67,89,342,123,12];const iteratorNums = nums.keys();for(let key of iteratorNums){
    
         output.innerHTML += key +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The keys of the nums array is:
    0
    1
    2
    3
    4
    5
    

    JavaScript Classes

    Classes are essential in the object-oriented programming language. It is a blueprint for the object.

    You can use the class keyword to define the class. You can add constructors, properties, and methods to the class body. To access class properties and methods, you can use the class instance.

    Example

    In the below code, we have defined the animal class.

    The constructor initializes the value of the name and isVegetarian property. The getInfo() method returns the animal information.

    We created the object of the animal class and used it to invoke the getInfo() method of the class.

    <html><body><div id ="output">The animal information is:</div><script>classanimal{constructor(name, isVegetarian){this.name = name;this.isVegetarian = isVegetarian;}getInfo(){return"Name : "+this.name +", "+"isVegetarian? : "+this.isVegetarian;}}const lion =newanimal("Lion",false);
    
        
      document.getElementById("output").innerHTML += lion.getInfo();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The animal information is: Name : Lion, isVegetarian? : false
    

    JavaScript const keyword

    The JavaScript const keyword is used to declare the constant variables. You need to initialize the constant variables while declaring them.

    Example

    In the below code, the 'fruit' is a constant variable. You can't reinitialize its value.

    <html><body><div id ="output">The value of the fruit variable is:</div><script>const fruit ="Apple";// fruit = "Banana"; This is Invalid
    
      document.getElementById("output").innerHTML += fruit;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of the fruit variable is: Apple
    

    JavaScript let keyword

    The JavaScript let keyword is used to define the blocked scope variables.

    Example

    In the below code, we have defined the variable 'a' using the let keyword inside the 'if' block. It can't be accessible outside the 'if' block due to its scoping behavior.

    <html><body><div id ="output"></div><script>if(true){let a =20;
    
         document.getElementById("output").innerHTML +="The value of a is: "+ a;}// You can't access it here.&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of a is: 20
    

    JavaScript Default Parameters

    The default parameters mean function parameters can have default values. When you don't pass enough arguments to the function, it uses the default parameter values.

    Example

    In the below code, the division () function takes two parameters. The default value of a is 10, and b is 2.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");functiondivision(a = 10, b = 2){return a / b;}
    
      output.innerHTML +="division(40, 5) =&gt; "+division(40,5)+"&lt;br&gt;";
      output.innerHTML +="division(40) =&gt; "+division(40)+"&lt;br&gt;";
      output.innerHTML +="division() =&gt; "+division();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    division(40, 5) => 8
    division(40) => 20
    division() => 5
    

    JavaScript forof Loop

    The JavaScript forof loop traverses the iterable like an array, string, set, map, etc.

    Example

    In the below code, we traverse the array of numbers and print each element of the array in the output.

    <html><body><div id ="output">The array elements are:</div><script>const array =[10,67,82,75,80];for(let number of array){
    
         document.getElementById("output").innerHTML += number +", ";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The array elements are: 10, 67, 82, 75, 80,
    

    JavaScript Function Rest Parameter

    When you are unsure about a number of the function argument, you can use the rest parameters. The rest parameter allows you to collect multiple arguments in a single array.

    Example

    We have passed the below code using the rest parameter with the sum() function. The name of the rest parameter can be a valid identifier, and it is used with the spread () operator.

    The sum() function adds the multiple numeric values and returns them.

    <html><body><div id ="output">sum(10,67,82,75,80)=</div><script>functionsum(...restParam){let res =0;for(let ele of restParam){
    
            res += ele;}return res;}
      document.getElementById("output").innerHTML +=sum(10,67,82,75,80);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    sum(10, 67, 82, 75, 80) = 314
    

    JavaScript Modules

    In JavaScript, you can create different modules to write reusable code. After that, you can import the modules into the different JavaScript files.

    Default Export/Import modules

    const moduleMath ="This is the default value.";exportdefault moduleMath;// Exporting the module

    In other JavaScript files,

    // Importing the default moduleimport moduleMath from'./filename.js';
    console.log(moduleMath);

    Named Export/Import modules

    You can also export particular functions or properties from the modules and import them into other JavaScript files.

    // Exporting variablesexportconst size =90;// Exporting functionexportfunctionadd(a, b){return a + b;}

    In other JavaScript files,

    // Importing specific properties and functionsimport{ size, add}from'./filename.js';
    
    console.log(myVariable);// 90
    console.log(add(15,25));// 40

    JavaScript Map Objects

    The map is used to store the key-value pairs. You can use the Map() constructor to define a map.

    Example

    In the example below, we use the map to store the fruit's name and price. The set() method is used to insert the key-value pair into the fruit map, and the get() method is used to get the value of a particular key from the map.

    <html><body><div id ="output1">The price of the Apple is:</div><div id ="output2">The price of the Banana is:</div><script>const fruit =newMap();
    
      fruit.set("Apple",50);
      fruit.set("Banana",60);
      document.getElementById("output1").innerHTML += fruit.get("Apple")+"&lt;br&gt;";
      document.getElementById("output2").innerHTML += fruit.get("Banana");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The price of the Apple is: 50
    The price of the Banana is: 60
    

    New Global Methods

    In the ES6, below two global methods are added.

    • isFinite()
    • isNaN()

    isFinite()

    The isFinite() method checks whether the value passed as an argument is finite.

    Example

    In the below code, the num1 variable contains the infinity value, and num2 contains the valid numeric value.

    We used the isFinite() method to check whether the num1 and num2 variable's value is finite.

    <html><body><div id ="output"></div><script>const num1 =6453/0;const num2 =90;
    
      document.getElementById("output").innerHTML ="isFinite(6453 / 0): "+isFinite(num1)+"&lt;br&gt;"+"isFinite(90): "+isFinite(num2);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    isFinite(6453 / 0): false
    isFinite(90): true
    

    isNaN()

    The isNaN() method checks whether the argument is a valid number. It returns false for the number value.

    Example

    In the below code, the isNaN() method returns true for the num1 variable, as it contains the string, and the string is not a number. For the num2 variable, the isNaN() method returns false, as it contains the numeric value.

    <html><body><div id ="output"></div><script>const num1 ="Hello";const num2 =867;
    
      document.getElementById("output").innerHTML ="isNaN(num1):  "+isNaN(num1)+"&lt;br&gt;"+"isNaN(num2):  "+isNaN(num2);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    isNaN(num1): true
    isNaN(num2): false
    

    New JavaScript Math Methods

    In ES6, 5 new methods were added to the Math object.

    • Math.cbrt() − It is used to find the cube root of the given number.
    • Math.log2() It is used to find the logarithm of a number and uses the base 2.
    • Math.log10() It finds the base 10 logarithm of numeric value.
    • Math.trunc() It removes the decimal part from the floating point number and converts it into the whole number.
    • Math.sign() It returns 1, 0, and -1 based on the sign of the number passed as an argument.

    Example: Math.cbrt()

    The below code finds the cube root of the 64.

    <html><body><div id ="output">The cube root of the 64 is:</div><script>
    
      document.getElementById("output").innerHTML += Math.cbrt(64);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Math.log2()

    The below code finds the logarithm of 30 base 2.

    <html><body><div id ="output">The value of logarithm of30 base 2 is:</div><script>
    
      document.getElementById("output").innerHTML += Math.log2(30);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Math.log10()

    The below code finds the logarithm of 10 base 10.

    <html><body><div id ="output">The value of the logarithm of10 base 10 is:</div><script>
    
      document.getElementById("output").innerHTML += Math.log10(10);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Math.trunc()

    The below code truncates the floating point numbers using the Math.trunc() method.

    <html><body><div id ="output">After converting 23.2 to integer is:</div><script>
    
      document.getElementById("output").innerHTML += Math.trunc(23.2);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Math.sign()

    <html><body><div id="output1">Math.sign(23):</div><div id="output2">Math.sign(-23):</div><script>
    
      document.getElementById("output1").innerHTML += Math.sign(23);
      document.getElementById("output2").innerHTML += Math.sign(-23);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    New Number Methods

    In ES6, two new number methods were added.

    • Number.isInteger() − It checks whether the number passed as an argument is a whole number or an integer.
    • Number.isSafeInteger() − It checks whether the number can be represented as a 64-bit double number.

    Example

    The below code checks whether 10 and 10.5 is an integer value. Also, it uses the isSafeInteger() method of the number class to check whether the number is safe integer.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");
    
      output.innerHTML +="Is 10 integer? "+ Number.isInteger(10)+"&lt;br&gt;";
      output.innerHTML +="Is 10.5 integer? "+ Number.isInteger(10.5)+"&lt;br&gt;";
        
      output.innerHTML +="Is 10000 safe integer? "+ Number.isSafeInteger(10000)+"&lt;br&gt;";
      output.innerHTML +="Is 10000000000000000000000 safe integer? "+ Number.isSafeInteger(10000000000000000000000);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Is 10 integer? true
    Is 10.5 integer? false
    Is 10000 safe integer? - true
    Is 10000000000000000000000 safe integer? - false
    

    New Number Properties

    In ES6, three new number properties were added.

    • EPSILON − It returns the value of the Epsilon.
    • MIN_SAFE_INTEGER − It returns the minimum integer value that a 64-bit number can represent.
    • MAX_SAFE_INTEGER − returns the maximum number, which can be represented by 64-bit.

    Example

    The below code shows the value of the Epsilon constant, minimum value of the safe integer, maximum value of the safe integer in JavaScript.

    <html><body><div id ="output1">The value of Epsilon is:</div><div id ="output2">The minimum safe integer is:</div><div id ="output3">The maximum safe integer is:</div><script>
    
      document.getElementById("output1").innerHTML +=  Number.EPSILON;
      document.getElementById("output2").innerHTML +=  Number.MIN_SAFE_INTEGER;
      document.getElementById("output3").innerHTML +=  Number.MAX_SAFE_INTEGER&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of Epsilon is: 2.220446049250313e-16
    The minimum safe integer is: -9007199254740991
    The maximum safe integer is: 9007199254740991
    

    JavaScript Promises

    In JavaScript, promises are used to handle the code asynchronously.

    It produces and consumes the code.

    Example

    In the below code, we used the Promise() constructor to create a promise. We resolve and reject the promise based on the random value generated using the random() method of the Math block.

    After that, we handle the promise using the then() and catch() block.

    <html><body><div id ="output"></div><script>// Creating a Promiseconst newPromise =newPromise((res, rej)=>{setTimeout(()=>{const rand_value = Math.random();if(rand_value <0.5){res("Value is less than 0.5");// Resolving the promise}else{rej("Value is greater than 0.5");// Rejecting the promise}},1000);// Adding 1 second delay});// Consuming the Promise
    
      newPromise
         .then((res)=&gt;{
             document.getElementById("output").innerHTML += res;}).catch((rej)=&gt;{
              document.getElementById("output").innerHTML += rej;});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Value is greater than 0.5
    

    JavaScript Set Objects

    The Set() constructor is used to create a set. The set stores only unique elements of different types.

    Example

    In the below code, we created a new set and passed the array containing the number as an argument of the Set() constructor. The set contains only unique elements, which you can see in the output.

    <html><body><div id ="output">The set elements are:</div><script>const num_set =newSet([10,20,20,42,12]);for(let num of num_set){
    
         document.getElementById("output").innerHTML +=", "+ num;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The set elements are: , 10, 20, 42, 12
    

    JavaScript New String Methods

    In ES6, three new string methodswere added.

    • endsWith() − checks whether the string ends with a particular substring.
    • includes() − checks whether the string contains the substring at any position.
    • startsWith() − checks whether the string starts with a particular substring.

    Example

    The example below demonstrates how to use String endsWith(), includes(), and startsWith() methods with the help of an staing "How are you? I'm fine!".

    <html><body><div id ="output1">Does string end with'fine'?</div><div id ="output2">Does string include 'are'?</div><div id ="output3">Does string start with'How'?</div><script>let str ="How are you? I'm fine!";
    
      document.getElementById("output1").innerHTML +=  str.endsWith("fine!");
      document.getElementById("output2").innerHTML += str.includes("are");
      document.getElementById("output3").innerHTML += str.startsWith("How");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Does string end with 'fine'? true
    Does string include 'are'? true
    Does string start with 'How'? true
    

    JavaScript Symbol

    The JavaScript Symbol is a primate data type in JavaScript. In JavaScript, each Symbol is unique. You may use it to create unique ids.

    Example

    In the code below, we have defined two symbols and passed the same value as an argument. Still, both symbols are unique, which you can see in the output.

    <html><body><div id ="output"></div><script>const sym1 =Symbol("a");const sym2 =Symbol("a");if(sym1 == sym2){
    
         document.getElementById("output").innerHTML +="sym1 and sym2 are equal. &lt;br&gt;";}else{
         document.getElementById("output").innerHTML +="sym1 and sym2 are not equal.";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    sym1 and sym2 are not equal.
    

    JabaScript Spread Operator

    The JavaScript spread operator allows you a create a copy of the iterable, like array, string, etc.

    Example

    The below code demonstrates using the spread operator to create an array of characters from the string.

    <html><body><div id ="output">The char array is:</div><script>let str ="Hello World!";const char =[...str];
    
      document.getElementById("output").innerHTML += char;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The char array is: H,e,l,l,o, ,W,o,r,l,d,!
  • ES5

    JavaScript ES5, also known as ECMAScript 5, was released in 2009. It was the first major revision of JavaScript. It introduced many new features, including getters and setters, and ‘use strict‘ directive. ES5 has provided significant improvement over the previous versions of JavaScript. The new features introduced in ES5 make code more powerful, concise and easier to maintain.

    New Added Features in JavaScript ES5

    Here are the new methods, features, etc., added to the ES5 version of JavaScript.

    • Array every()
    • Array filter()
    • Array forEach()
    • Array isArray()
    • Array indexOf()
    • Array lastIndexOf()
    • Array map()
    • Array reduce()
    • Array reduceRight()
    • Array some()
    • Date now()
    • Date toJSON()
    • Date toISOString()
    • Function bind()
    • JSON parse()
    • JSON stringify()
    • Multiline strings
    • Object methods
    • Object defineProperty()
    • Property getters and setters
    • Reserved words as property names
    • “use strict”
    • String[number] access
    • String trim()
    • Trailing commas

    Here, we have explained each feature in detail.

    JavaScript Array every()

    The array.every() method checks whether each element of the array follows a particular condition.

    Example

    In the below code, we use the array.every() method to check whether each element of the array is even.

    <html><body><div id ="output"> All elements of the array are even?</div><script>const arr =[10,20,30,40,2,6];functioneven(element){return element %2==0;}
    
      document.getElementById("output").innerHTML += arr.every(even);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    All elements of the array are even? true
    

    JavaScript Array filter()

    The array.filter() filters array elements and gets filtered elements in the new array.

    Example

    In the below code, we filter the array elements which are divisible by 10.

    <html><body><div id ="output"> Elements divisible by 10 are </div><script>const arr =[10,20,8,30,40,2,6];functiondivide(element){return element %10==0;}
    
      document.getElementById("output").innerHTML +=  arr.filter(divide);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Elements divisible by 10 are 10,20,30,40
    

    JavaScript Array forEach()

    The array.forEach() traverses the array elements. It is similar to loops in JavaScript.

    Example

    The below code uses the array.forEach() method to traverse the array and print each array element in the new line.

    <html><body><div id="output"></div><script>const arr =["TATA","Honda","Toyota","Maruti"];
    
      arr.forEach(traverse);// Using the array.forEach() methodfunctiontraverse(element){
         document.getElementById("output").innerHTML += element +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    TATA
    Honda
    Toyota
    Maruti
    

    JavaScript Array isArray()

    The Array.isArray() method checks whether the object passed as an argument is an array.

    Example

    The below code checks whether the arr is an array using the Array.isArray() method.

    <html><body><div id ="output"></div><script>const arr =["TATA","Honda","Toyota","Maruti"];let bool = Array.isArray(arr);
    
      document.getElementById("output").innerHTML +="Is arr array? "+ bool;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Is arr array? true
    

    JavaScript Array indexOf()

    The array.indexOf() method returns the first index of the particular element in the array.

    Example

    The below code finds the first index of 23 in the array, which is 0.

    <html><body><div id ="output"> The first index of23in the array is </div><script>const arr =[23,45,32,12,23,56];
    
      document.getElementById("output").innerHTML += arr.indexOf(23);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The first index of 23 in the array is 0
    

    JavaScript Array lastIndexOf()

    The array.lastIndexOf() method returns the last index of the particular element in the array.

    Example

    The code below finds the last index of the 45 in the array, which is 4.

    <html><body><div id ="output"> The last index of45in the array is </div><script>const arr =[23,45,32,45,45,56];
    
      document.getElementById("output").innerHTML += arr.lastIndexOf(45);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The last index of 45 in the array is 4
    

    JavaScript Array map()

    The array.map() method returns a new array after mapping current array elements with new ones.

    Example

    The below code uses the map() method to create a new array by doubling the array elements.

    <html><body><div id ="output"> The newarray is </div><script>const arr =[1,2,3,4,5];functiondoubleEle(element){return element *2;}
    
      document.getElementById("output").innerHTML += arr.map(doubleEle);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The new array is 2,4,6,8,10
    

    JavaScript Array reduce()

    The array.reduce() method reduces the array to a single value.

    Example

    The below code multiples all elements of the array using the array.reduce() method.

    <html><body><div id ="output">The multiplication result of the array elements is </div><script>const arr =[1,2,3,4,5];functionmultiplier(multiplication, element){return multiplication *2;}
    
      document.getElementById("output").innerHTML += arr.reduce(multiplier);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The multiplication result of the array elements is 16
    

    JavaScript Array reduceRight()

    The array.reduceRight() method reduces the array from right to left instead of left to right.

    Example

    <html><body><div id ="output">The merged array elements in the reverse order is:</div><script>const arr =["How","are","you","doing?"];functionmerge(res, element){return res += element +" ";}
    
      document.getElementById("output").innerHTML += arr.reduceRight(merge);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The merged array elements in the reverse order is: doing?you are How
    

    JavaScript Array some()

    The array.some() method is used to check whether some elements of the array follow the particular condition.

    Example

    The code below checks whether the array contains 1 or more strings with lengths greater than 3.

    <html><body><div id ="output">Array contains one or more strings with lengths greater than 3?</div><script>const arr =["How","are","you","doing?"];functionfunc_len(element){return element.length >3;}
    
      document.getElementById("output").innerHTML += arr.some(func_len);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Array contains one or more strings with lengths greater than 3? true
    

    JavaScript Date now()

    The Date.now() method is used to get the total number of milliseconds since 1st January 1970.

    Example

    The below code finds the total milliseconds from 1st January 1970.

    <html><body><div id ="output">Total milliseconds since 1st January,1970 is:</div><script>
    
      document.getElementById("output").innerHTML += Date.now();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Total milliseconds since 1st January, 1970 is: 1702540225136
    

    JavaScript Date toJSON()

    The date.toJSON() method converts the date into the JSON date format. The JSON date format is the same as the ISO format. The ISO format is YYYY-MM-DDTHH:mm:ss.sssZ.

    Example

    The below code prints the current date in JSON format.

    <html><body><div id ="output">The current date inJSON format is:</div><script>const date =newDate();
    
      document.getElementById("output").innerHTML += date.toJSON();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The current date in JSON format is: 2023-12-18T06:12:52.366Z
    

    JavaScript Date toISOString()

    The date.toISOString() method is used to convert the date into the ISO standard format.

    Example

    The below code prints the current date in the standard ISO string format.

    <html><body><div id ="output">The current date inISO string format is:</div><script>const date =newDate();
    
      document.getElementById("output").innerHTML += date.toISOString();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The current date in ISO string format is: 2023-12-18T06:13:50.159Z
    

    JavaScript Function bind()

    The bind() method is used to borrow the method from another object.

    Example

    In the below code, the bird object contains the properties and printInfo() method. The animal object contains only name and category properties.

    We used the bind() method to borrow the printInfo() method from the bird object for the animal object. In the output, the printInfo() method prints the information of the animal object.

    <html><body><div id ="result"></div><script>const output = document.getElementById("result");const bird ={
    
         name:"Parrot",
         category:"Bird",printInfo(){return"The name of the "+this.category +" is - "+this.name;}}const animal ={
         name:"Lion",
         category:"Animal",}const animalInfo = bird.printInfo.bind(animal);
      output.innerHTML +=animalInfo();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The name of the Animal is - Lion
    

    JavaScript JSON parse()

    The JSON.parse() method is used to convert the string into the JSON object.

    Example

    The code given below converts the string into an object. Also, we have printed the values of object properties in the output.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");const objStr ='{"name":"Sam", "age":40, "city":"Delhi"}';const obj =JSON.parse(objStr);
    
      output.innerHTML +="The parsed JSON object values are - &lt;br&gt;";
      output.innerHTML +="name : "+ obj.name +"&lt;br&gt;";
      output.innerHTML +="age : "+ obj.age +"&lt;br&gt;";
      output.innerHTML +="city: "+ obj.city +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The parsed JSON object values are -
    name : Sam
    age : 40
    city: Delhi
    

    JavaScript JSON stringify()

    The JSON.stringify() method converts the object into a string.

    Example

    The code below converts the obj object into the string using JSON.strringify() method.

    <html><body><div id ="output">The object in the string format is -</div><script>const obj ={
    
         message:"Hello World!",
         messageType:"Welcome!",}
      document.getElementById("output").innerHTML +=JSON.stringify(obj);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The object in the string format is - {"message":"Hello World!","messageType":"Welcome!"}
    

    JavaScript Multiline Strings

    You can use the backslash (\) to break the line of the string and define the string in multiline.

    Example

    In the below example, we have defined the str string in multiple lines and used the backslash to break the line.

    <html><body><div id ="output"></div><script>let str ="Hi \
    
                 user";
      document.getElementById("output").innerHTML +="The string is - "+ str;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The string is - Hi user
    

    JavaScript Object Methods

    In ES5, object-related methods are added to manipulate and protect the objects.

    Methods to Manipulate the Object

    Sr.No.MethodDescription
    1create()To creat a new object, using an existing object as the prototype.
    2defineProperty()To make a clone of the object and add new properties to its prototype.
    3defineProperties()To define a property into a particular object and get the updated object.
    4getOwnPropertyDescriptor()To get the property descriptor for the properties of the object.
    5getOwnPropertyNames()To get object properties.
    6getPrototypeOf()To get the prototype of the object.
    7keys()To get all keys of the object in the array format.

    Methods to Protect the Object

    Sr.No.MethodDescription
    1freeze()To prevent adding or updating object properties by freezing the object.
    2seal()To seal the object.
    3isFrozen()To check if the object is frozen.
    4isSealed()To check if the object is sealed.
    5isExtensible()To check if an object is extensible.
    6keys()To get all keys of the object in the array format.
    7preventExtensions()To prevent the prototype updation of the object.

    JavaScript Object defineProperty()

    You can use the Object.definedProperty() method to define a single property of the object or update the property value and metadata.

    Example

    The code below contains the car object's brand, model, and price properties. We used the defineProperty() method to define the gears property in the object.

    <html><body><div id ="output">The obj object is -</div><script>const car ={
    
         brand:"Tata",
         model:"Nexon",
         price:1000000,}
      Object.defineProperty(car,"gears",{
         value:6,
         writable:true,
         enumerable:true,
         configurable:true})
        
      document.getElementById("output").innerHTML +=JSON.stringify(car);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The obj object is - {"brand":"Tata","model":"Nexon","price":1000000,"gears":6}
    

    JavaScript Property getters and setters

    The getters and setters are used to access and update the object properties securely.

    Example

    In the below code, the watch object contains the brand and dial properties. We have defined the getter using the get keyword to access the brand property value.

    Also, we have defined the setter using the set keyword to set the dial property value in the upper case.

    In this way, you can secure the updating object property value.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");const watch ={
    
         brand:"Titan",
         dial:"ROUND",// Getter to get brand propertygetwatchBrand(){returnthis.brand;},// Setter to set Watch dialsetwatchDial(dial){this.dial = dial.toUpperCase();}}
      output.innerHTML ="The Watch brand is - "+ watch.watchBrand +"&lt;br&gt;";
      watch.watchDial ="square";
      output.innerHTML +="The Watch dial is - "+ watch.dial;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The Watch brand is - Titan
    The Watch dial is - SQUARE
    

    JavaScript Reserved words as property names

    After ES5, you can use the reversed words as a property name in the object.

    Example

    In the below code, delete is used as an object property name.

    <html><body><div id ="output">The obj object is -</div><script>const obj ={
    
         name:"Babo",delete:"Yes",}
      document.getElementById("output").innerHTML +=JSON.stringify(obj);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The obj object is - {"name":"Babo","delete":"Yes"}
    

    JavaScript "use strict"

    The strict mode was also introduced in the ES5.

    The strict mode allows you to overcome errors and write clear code. You can use the use strict directive to declare the strict mode.

    Example

    In the below code, you can uncomment the num = 43 line and observe the error. The strict mode doesnt allow developers to define the variables without using var, let, or const keywords.

    <html><body><div id ="output">The value of num is:</div><script>"use strict";let num =43;// This is valid// num = 43; // This is invalid
    
      document.getElementById("output").innerHTML += num +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of num is: 43
    

    JavaScript String[number] access

    Before ES5, the charAt() method was used to access the string character from a particular index.

    After ES5, you can consider the string as an array of characters and access string characters from the specific index as you access array elements.

    Example

    <html><body><div id ="output1">The first character in the string is:</div><div id ="output2">The third character in the string is:</div><script>let str ="Apple";
    
      document.getElementById("output1").innerHTML += str[0];
      document.getElementById("output2").innerHTML += str[2];&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The first character in the string is: A
    The third character in the string is: p
    

    JavaScript String trim()

    The string.trim() method removes the whitespaces from both ends.

    Example

    In the below code, we used the string.trim() method to remove the whitespaces from the start and end of the str string.

    <html><body><div id ="output"></div><script>let str ="    Hi, I am a string.    ";
    
      document.getElementById("output").innerHTML = str.trim();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Hi, I am a string.
    

    JavaScript Trailing commas

    You can add a trailing comma (A comma after the last element) in the array and object.

    Example

    In the below code, we have added the trailing comma after the last object property and array element. The code runs without error and prints the output.

    <html><body><div id ="demo1"></div><div id ="demo2"></div><script>const obj ={
    
         name:"Pinku",
         profession:"Student",}
      document.getElementById("demo1").innerHTML =JSON.stringify(obj);let strs =["Hello","world!",];
      document.getElementById("demo2").innerHTML = strs;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    {"name":"John","profession":"Student"}
    Hello,world!
    

    Note The JSON string doesnt allow the trailing comma.

    For example,

    let numbers ='{"num1": 10,"num2": 20,}';JSON.parse(numbers);// Invalid
    
    numbers ='{"num1": 10,"num2": 20}';JSON.parse(numbers);// Valid

    In ES5, mostly array and object-related methods are introduced.