Showing posts with label frontend. Show all posts
Showing posts with label frontend. Show all posts

Sunday, June 19, 2022

ES12 new Features

ES12 is a version issued by the ECMA Association in 2021. Because it is the twelfth version of ECMAScript, it is also called ES12.

The following is the list of the latest javascript features.

  1. String.prototype.replaceAll()
  2. WeakRefs
  3. Logical Assignment Operator
  4. Numeric Separators
  5. Promise. any
  6. Private class methods

String.prototype.replaceAll():

This method addresses a specific lack in String.prototype.replace.

With the String.replaceAll you can easily replace all occurrences of a given string.

Syntax: String.prototype.replaceAll(searchString, replace string)

For example:
const string=" flyer is a good fly"
console.log(string.replaceAll("fly", "butterfly"));

Output: butterfly is a good butterfly

WeakRefs:

WeakRef is the shorthand for Weak References, and its primary use is to hold a weak reference to another object.

That means it does not prevent the garbage collector from collecting the object.

The Weak Reference is useful when we do not want to keep the object in the memory forever.

But why do we need the WeakRef in the first place?

In JavaScript, the object is not collected by the garbage collector as long as a reference to that object exists.

Thus, it keeps the object in the memory, which leaves you with less memory. The WeakRef implementation allows you to avoid that.

You can create a Weak Reference by using the new WeakRef, and you can read a reference by calling the deref() method.

A simple example would be:

const large object = new WeakRef({
name: "CacheMechanism",
type: "Cache",
implementation: "WeakRef"
});

large object.deref();

Logical Assignment Operator:

You might be familiar with logical operations like ??, &&, or || and the assignment operator =. The Logical Assignment Operator introduced in ES2021 combines logical operations like ??, && or || with an assignment operator =.

Let’s see an example:

var a = true
var b = false
// Old
if (!a) {
  a = b
}
// New
a ||= b // returns a
// Old
if (a) {
  a = b
}
// New
a &&= b // returns b

Numeric Separators:

This feature literally improves developer experience by enabling developers to make their numeric literals more readable by creating a visual separation between groups of digits.

It’s similar to the way we use commas to separate numbers in writing. For example:

const balance = 9_300_254_812

JavaScript
Using the underscore, deciphering the above number becomes a no-brainer, in contrast to not using the underscore as shown below.

const balance = 9300354812

Promise. any:

Promise. any() takes an iterable of Promise objects.

It returns a single promise that resolves as soon as any of the promises in the iterable fulfills, with the value of the fulfilled promise.

If no promises in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected with an AggregateError, a new subclass of Error that groups together individual errors.

Example:

const promise1 = Promise.reject(0);
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'quick'));
const promise3 = new Promise((resolve) => setTimeout(resolve, 500, 'slow'));
const promises = [promise1, promise2, promise3];
Promise.any(promises).then((value) => console.log(value));

Private Class Methods and Accessors:

The class methods and properties are public by default, but the private methods and properties can be created

by using a hash # prefix. The privacy encapsulation has been enforced from the ECMAScript 2021 update.

Tuesday, June 14, 2022

Simple Introduction to Web Workers in JavaScript

 JavaScript is an object-based scripting language which is lightweight and cross-platform. It is an interpreted, full-fledged programming language that enables dynamic interactivity on websites when applied to an HTML document.

Even though js had so many advantages, it is having some drawbacks. It is Single threaded language. This means it has one call stack and one memory heap. As expected, it executes code in order and must finish executing a piece code before moving onto the next.

To resolve the above one,we can use Web worker.

A web worker is a JavaScript code that runs in the background and does not influence the page’s performance.

Web Workers are background scripts and they are relatively heavy-weight, and are not intended to be used in large numbers. Although Web Workers cannot block the browser UI, they can still consume CPU cycles and make the system less responsive.

In HTML5 Web Workers are of two types:

Dedicated Web Workers:
The dedicated worker can be accessed by only one script which has called it. The dedicated worker thread end as its parent thread ends. Dedicated workers are only used by one or single main thread.

Shared Web Workers:
It can be shared by multiple scripts and can communicate using the port. Shared workers can be accessed by different windows, iframes or workers.

Common examples of web workers would be:

1)Dashboard pages that display real-time data such as stock prices, real-time active users, and so on
2)Fetching huge files from the server
3)Autosave functionality

You can create a web worker using the following syntax:

const worker = new Worker(".js");

Worker is an API interface that lets you create a thread in the background. We need to pass a parameter, that is a .js file. This specifies the worker file the API needs to execute.

A worker can be shared or used by multiple consumers/scripts. These are called shared workers. The syntax of the shared worker is very similar to that of the above mentioned workers.

const worker = new SharedWorker(".js");

Terminating the Web Worker:
If you want to immediately terminate the currently running worker in the main thread, then you can terminate it by calling the terminate() method of Web Worker. Here is the syntax for web worker termination:

worker.terminate();

Worker Example:

<!DOCTYPE html>  
<html>  
<head>  
  <style>  
    .div1{  
      margin-left: 350px;  
    }  
  </style>  
</head>  
<body>  

<div class="div1">  
  <h2>Example of Web Worker</h2>  
<label>Enter the number to find the square</label>  
<br><input type="text" name="num" id="num"><br>  
<br><button id="submit">Submit</button>  
<button id="other">Wait</button>  
<div id="text"></div>  
</div>  
<script type="text/javascript">  
  
document.getElementById("other").onclick=function() {  
  alert("Hey! Web Worker is working, and you can wait for the result.");  
}  
  
//Web-worker Code
  var worker= new Worker("worker.js");  
  worker.onmessage= function(event){  
  document.getElementById("text").innerText= event.data;}  
  document.getElementById("submit").onclick= function(){  
  var num= document.getElementById("num").value;  
  worker.postMessage(num);  
 }  
</script>  
<p>
</body>  
</html> 
  • var worker= new Worker("worker.js"); To create the web Worker object.
  • worker.onmessage= function(event): It is used to send the message between the main thread and Worker thread.
  • worker.postMessage(num); This is the method used to communicate between the Worker thread and main thread. Using this method Worker thread return the result to the main thread.

Note: Use the below link to test whether your browser is compatible with html5 feature.

http://html5test.com/

ES12 new Features