Category: Advanced Chapters

  • Async Iteration

    Asynchronous Iteration

    In JavaScript, asynchronous iteration refers to the ability to iterate over asynchronous sequences or collections, such as those returned by asynchronous functions or generators. Async iteration is typically used with operations that involve asynchronous tasks, such as fetching data from a remote server or reading from a file.

    Understanding Asynchronous Operations

    In basic terms, asynchronous operations in programming denote tasks or procedures that do not obstruct the program’s execution during their pending completion. Rather than pausing for each operation to conclude before proceeding onto the subsequent one; these asynchronous tasks enable a program: it continues executing other duties, concurrently waiting for the current task’s finalization.

    Using the ‘for await…of’ Loop

    The for await…of loop is used for asynchronous iteration. It works similarly to the regular for…of loop, but it is designed to work with asynchronous iterators. An asynchronous iterator is an object that defines an async next() method, which returns a promise for the next value in the sequence.

    Example: Using Promises

    JavaScript incorporates promises as a characteristic to manage asynchronous operations; these promises symbolize the potential outcomes, either completion or failure of an asynchronous task. Notably, the function asyncOperation emulates such tasks by returning a promise. The ‘for await…of’ loop elegantly navigates the asynchronous sequence, emphasizing promise utilization in managing non-blocking operations without compromising code lucidity.

    <!DOCTYPE html><html><body><h2>Async Iteration with Promises</h2><div id="output"></div><script>functionasyncOperation(value){returnnewPromise(resolve=>{setTimeout(()=>{
    
        document.getElementById('output').innerHTML +=&amp;lt;p&amp;gt;Processed: ${value}&amp;lt;/p&amp;gt;;resolve(value);},1000);});}const asyncIterable ={[Symbol.asyncIterator]:asyncfunction*(){for(let i =1; i &lt;=3; i++){yieldawaitasyncOperation(i);}},};asyncfunctionprocessAsyncIterable(){forawait(const result of asyncIterable){
      document.getElementById('output').innerHTML +=&amp;lt;p&amp;gt;Received: ${result}&amp;lt;/p&amp;gt;;}}processAsyncIterable();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example 2: Using Fetch API for Asynchronous HTTP Requests

    Here, we demonstrate asynchronous iteration with the Fetch API for executing HTTP requests: The asyncIterable operates to fetch data in an asynchronous manner. Furthermore; employing a 'for await...of' loop - it elegantly traverses through results showcasing how seamlessly async iteration amalgamates with external source data retrieval.

    <!DOCTYPE html><html><body><h2>Async Iteration with Fetch API</h2><div id="output"></div><script>const url ='https://jsonplaceholder.typicode.com/todos/';const asyncIterable ={[Symbol.asyncIterator]:asyncfunction*(){for(let i =1; i <=3; i++){const response =awaitfetch(${url}${i});const data =await response.json();
    
        document.getElementById('output').innerHTML +=&amp;lt;p&amp;gt;Received: ${JSON.stringify(data)}&amp;lt;/p&amp;gt;;yield data;}},};asyncfunctionprocessAsyncIterable(){forawait(const result of asyncIterable){// Already displaying results above, no need for additional output.}}processAsyncIterable();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example 3: Using callback

    The approach employs a callback-based mechanism to achieve asynchronous iteration. The function asyncOperation imitates an asynchronous task and calls back upon completion. Meanwhile, the processAsyncIterable function actively iterates through an array, invoking the asynchronous operation for every element.

    <!DOCTYPE html><html><body><h2>Async Iteration with callback</h2><div id="output"></div><script>functionasyncOperation(value, callback){setTimeout(()=>{
    
      document.getElementById('output').innerHTML +=&amp;lt;p&amp;gt;Processed: ${value}&amp;lt;/p&amp;gt;;callback(value);},1000);}functionprocessAsyncIterable(iterable, callback){const iterator = iterable[Symbol.iterator]();functioniterate(){const next = iterator.next();if(next.done){return;}const value = next.value;asyncOperation(value,result=&gt;{
        document.getElementById('output').innerHTML +=&amp;lt;p&amp;gt;Received: ${result}&amp;lt;/p&amp;gt;;iterate();});}iterate();}const asyncIterable =[5,6,7,8,9,10];processAsyncIterable(asyncIterable,result=&gt;{// You can handle final result or additional actions here if needed.});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example 4: Promise With Error

    The method .then() in JavaScript employs one or two callback functions to manage the successful resolution of a Promise: upon the promise's resolution, it executes its first function; should rejection occur an optional second function is then executed.

    The method .catch() accompanies Promises, specifically to address promise rejections. A single callback function executes upon the rejection of the promise; this provides an elegant solution for managing errors in asynchronous operations - eliminating the need for a distinct .then() block dedicated to error handling.

    <!DOCTYPE html><html><head><style>
    
    #output {
      margin-top:20px;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h2&gt;Async Iteration with Promises&lt;/h2&gt;&lt;button onclick="startAsyncIteration()"&gt;Start Async Iteration&lt;/button&gt;&lt;div id="output"&gt;&lt;/div&gt;&lt;script&gt;functiondelay(ms){returnnewPromise(resolve=&gt;setTimeout(resolve, ms));}functionfetchData(index){returnnewPromise((resolve, reject)=&gt;{if(index &lt;5){delay(1000).then(()=&gt;resolve(Data ${index}));}else{// Simulate an error for index 5reject(newError('Error fetching data for index 5'));}});}functionstartAsyncIteration(){
    document.getElementById('output').innerHTML ='';let index =0;functioniterate(){fetchData(index).then(data=&gt;{displayData(data);
          index++;if(index &lt;6){iterate();}}).catch(error=&gt;{// Display error on the page.displayError(error.message);});}iterate();}functiondisplayData(data){const outputDiv = document.getElementById('output');
    outputDiv.innerHTML +=&amp;lt;p&amp;gt;Data received: ${data}&amp;lt;/p&amp;gt;;}functiondisplayError(errorMessage){const outputDiv = document.getElementById('output');
    outputDiv.innerHTML +=&amp;lt;p style="color: red;"&amp;gt;Error: ${errorMessage}&amp;lt;/p&amp;gt;;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Real World Use Cases

    In real-world scenarios, we apply JavaScript async iterations to optimize various asynchronous operations: fetching data concurrently from multiple APIs in web applications; processing real-time updates - a function critical for chat systems and executing batch tasks or parallel tasks that require intensive resources. Furthermore, managing file operations and streams is possible with this technique along with handling concurrent user interactions on interactive web pages. Other applications involve processing data from IoT devices dynamically loading content onto webpages, these too benefit greatly from the use of asynchronous iteration due to their need for non-blocking efficiency as well responsiveness when dealing with complex task management such as offline-first application's data synchronization.

  • Validate URLs

    In this chapter, we will learn how we can validate URLs in JavaScript. Before knowing how to validate URLs, let’s understand what a URL is.

    What is a URL?

    A URL or Uniform Resource Locator identifies web pages, images, and videos on the internet. URLs are website addresses that transfer files, send emails, and many more.

    URLs consist of a protocol, domain name, and so on. URL indicates how the browser gets the data and where to get the data.

    We use a URL in the anchor tags or buttons to navigate to another location. We must verify the URL’s validity before using it.

    Validating URLs in JavaScript

    There are ways to validate URLs in JavaScript. Let us understand the rule to validate URLs:

    Rules to validate URLs

    Below are the rules to validate URLs:

    • URL must start with http://, https://, or www.
    • URL must contain a domain name.
    • URL must contain a top-level domain like .com, .org, .net, etc.
    • URL must not contain any spaces.

    Using Regular Expression

    Regular expression are much useful in validating URLs. A regular expression describes a pattern of characters. We use these patterns to match some text.

    Syntax

    Below you can see the regular expression syntax to validate URLs:

    string.match(regExp);var pattern =newRegExp(regExp);
    pattern.test(string);

    The first syntax matches a regular expression. The second syntax tests for a URL pattern.

    Example

    In the following example, we use a regular expression to validate URLs.

    <!DOCTYPE html><html><head><title>Validate URLs in JavaScript</title></head><body><h2>Validate URLs using Regular Expression</h2><div id="output"></div><script>let output = document.getElementById("output");var url ="https://www.tutorialspoint.com";var pattern =newRegExp("^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$");if(pattern.test(url)){
       output.innerHTML ="URL is valid";}else{
       output.innerHTML ="URL is not valid";}</script></body></html>

    Using URL() Constructor

    The URL() constructor returns a newly created URL object. The constructor throws a TypeError if the base URL or resultant URL is invalid.

    Syntax

    Below is the syntax to use the URL() constructor:

    var url =newURL(urlStr);newURL(url, base);return url.protocol ==='http:'|| url.protocol ==='https:';

    The first two syntaxes create a new URL, either with or without a base. The second syntax is to check the URL protocol validity.

    Example

    In this program, the URL method validates the URLs and returns a type error in the case of invalid URLs.

    <!DOCTYPE html><html><head><title>Validate URLs in JavaScript</title></head><body><h2>Validate URLs using URL() Constructor</h2><div id="output"></div><script>let output = document.getElementById("output");try{var url =newURL("https://www.tutorialspoint.com");if(url.protocol ==='http:'|| url.protocol ==='https:'){
    
      output.innerHTML ="URL is valid";}else{
      output.innerHTML ="URL is not valid";}}catch(e){
    output.innerHTML ="URL is not valid";}</script></body></html>

    This chapter taught us two methods to validate a URL. The first method suggests using a regular expression match or a pattern test. The second method is the built-in URL method. The URL method is easy because we can avoid the test case missing in the case of regular expressions.

    Both methods are useful in validating URLs. We can use any of the methods based on our requirements.

  • Unit Testing

    Unit testing is must in software development life-cycle. It is a process in which we can test small units of code individually to ensure that they are working correctly. In JavaScript, we can use various unit testing frameworks to test our code. Unit testing help us to find bugs early in the development process. Instead of testing the whole application, we can test small units of code.

    Why Unit Testing?

    • Catch bug early : testing smaller parts of code, it becomes easy to catch bug early in the development process.
    • Easier Refactoring: With the help of unit testing, you get confidence to make changes in code, because we know the existing code you have tested is already working.
    • Improves Code Quality: Writing unit tests help us to write better code. It helps us to write modular code which is easy to test.

    Unit Testing Frameworks

    There are many unit testing frameworks are available in JavaScript. Some of them are most popular and widely used. Some of them are −

    • Jest: Jest is a JavaScript testing framework developed by Facebook. It is widely used for testing JavaScript code. Jest is fast, easy to use and it absolutely provides everything you need for testing.
    • Mocha: Mocha has many feature, It is a JavaScript test framework that run on Node.js and in the browser, and makes asynchronous testing simple and fun. Mocha tests run serially, that allow it for flexible and accurate reporting, when mapping uncaught exceptions to the correct test cases.
    • Jasmine: Jasmine is a behavior-driven development framework for testing JavaScript code. It does not rely on browsers, DOM, or any JavaScript framework. Jasmine is inspired by other testing frameworks such as ScrewUnit, JSSpec, JSpec, and RSpec.
    • QUnit: QUnit is a powerful, easy-to-use JavaScript unit testing framework. It’s used by the jQuery project to test its code and plugins but is capable of testing any generic JavaScript code.

    Structure of Unit Testing

    In common unit test cases there are a few steps those are −

    • Setup: In this part, we set up the environment for the test. We can create objects, initialize variables, etc.
    • Execute: In this part, we execute the code that we want to test.
    • Assert: In this part, we check the result of the execution. We check if the result is as expected or not.
    • Teardown: In this part, we clean up the environment after the test. We can destroy objects, clear variables, etc.

    Example of unit test using Jest

    Below is a code snippet of unit test using Jest.

    Example

    functionsum(a, b){return a + b;}
    module.exports = sum;// test.jsconst sum =require('./sum');test('adds 1 + 2 to equal 3',()=>{expect(sum(1,2)).toBe(3);});

    Output

    PASS  ./sum.test.js
       adds 1 + 2 to equal 3 (3ms)
    

    In this example, we have a function sum which takes two arguments and returns the sum of those two arguments. We have written a test case for this function to check if the function is working correctly or not.

  • Undefined Check

    When the value is absolutely not present in the variable or string or anything else, we call it as Undefined. In JavaScript, undefined is a one of the primitive data type. It is used to represent the absence of a value.

    It get assigned to a variable when it is declared but not assigned any value.

    How to check if a variable is undefined?

    There are more than one way to check if a variable is undefined or not. Let’s see them one by one.

    • Using typeof operator
    • Using strict equality operator
    • Using void operator

    Using typeof operator

    When the variable is undefined, it means the variable is not declared. Users cant use it in the if-else conditional statement like the above method.

    To check the type of the undeclared variables, we can use the typeof operator. The typeof operator takes the variable as an operand and returns the variable type. As the operand of typeof, we can use undeclared variables also.

    Syntax

    Below syntax is used to check undefined variable using the typeof operator.

    typeof variable_name ==='undefined'

    Example

    Below is the example code given, that shows how to use the typeof operator to check the undefined value of the variable.

    <html><body><script>var a;if(typeof a ==='undefined'){
    document.write('a is undefined');}</script></body></html>

    Output

    Following is the output of the above code

    a is undefined
    

    Using strict equality operator

    In this method, we will use the strict equality operator to check whether a variable is null, empty, or undefined. If we dont assign the value to the variable while declaring, the JavaScript compiler assigns it to the undefined value. So, we can check that if the variable contains the null value or undefined value, it means we have a null variable.

    Syntax

    Below is the syntax given for checking the undefined value of the variable using the strict equality operator.

    variable_name ===undefined

    Example

    <html><body><script>var a;if(a ===undefined){
    document.write('a is undefined');}</script></body></html>

    Output

    Following is the output of the above code

    a is undefined
  • Short Circuiting

    In JavaScript, short-circuiting is a feature that checks conditions and stops as soon as it knows the answer. It doesn’t look for the rest of the expression, and that prevent unnecessary evaluations.

    Short-Circuiting for && operator

    Short circuit evaluation with &&(AND) logical operator means if the first expression evaluates to false then whole expression will be false and the rest of the expressions will not be evaluated.

    Code-snippet

    Below is an example snippet of short-circuiting with the && operator.

    let x =0&&"hello";// x will be 0, as 0 is falsy and short-circuitslet y =true&&"world";// y will be "world" because the first value is truthylet z ="hello"&&"world";// z will be "world" because both values are truthy
    console.log(x);// 0
    console.log(y);// world
    console.log(z);// world

    Output

    Following is the output of the above code

    0
    world
    world
    

    Short-Circuiting for || operator

    Short circuit evaluation with ||(OR) logical operator means if the first expression evaluates to true then whole expression will be true and the rest of the expressions will not be evaluated.

    Code-snippet

    Below is an example snippet of short-circuiting with the || operator.

    let x =0||"hello";// x will be "hello" because 0 is falsylet y =true||"world";// y will be true because the first value is truthylet z ="hello"||"world";// z will be "hello" because the first value is truthy
    console.log(x);// hello
    console.log(y);// true
    console.log(z);// hello

    Output

    Following is the output of the above code

    hello
    true
    hello
    

    Short-Circuiting Assignment

    Short-circuiting can be used in assignment operations as well. Means, if you have to assign something based on a condition, you can use short-circuiting.

    Code-snippet

    Below is an example snippet of short-circuiting in assignment operations.

    let x =0;let y =10;let z = x || y;// z will be 10 because x is falsy
    console.log(z);// 10

    In above example, z will be assigned the value of y because x is falsy.

    Output

    Following is the output of the above code

    10
    

    Short-Circuiting in Function Calls

    Short-circuiting can be used in function calls as well. Means, if you have to call a function based on a condition, you can use short-circuiting.

    Code-snippet

    Below is an example snippet of short-circuiting in function calls.

    functiongreet(name){return name ||"Guest";}let x =greet("John");// x will be "John" because name is truthylet y =greet("");// y will be "Guest" because name is falsy
    console.log(x);// John
    console.log(y);// Guest

    In above example, if name is truthy, it will return the name, otherwise it will return “Guest”.

    Output

    Following is the output of the above code

    John
    Guest
  • Rest Operator

    There are times when we want to pass any number of arguments to a function or want to get specific elements separately from an array or object. In such cases, we can use the rest operator.

    What is Rest Operator?

    The rest operator () allows us to call a function with any number of arguments and then access those excess arguments as an array. The rest operator also allows us in destructuring array or objects.

    Rest Operator with Function Parameters

    When you define a function, you can use rest operator to get all remaining arguments inside an array. This process helps us to pass any number of arguments without knowing how many they are.

    Code-Snippet

    Below is an example snippet of using rest operator in function parameters. We will sum all the numbers passed to the function.

    functionsum(...args){let total =0;for(let i of args){
    
     total += i;}return total;}
    console.log(sum(1,2,3,4,5));// 15 console.log(sum(1,2,3));// 6

    Output

    15
    6
    

    Rest Operator with Array Destructuring

    If you have given an array, and if you want specific element separately and rest of the elements in a separate array, you can use rest operator.Rest operator also help us to destructure an array.

    Code-Snippet

    Below is an example snippet of using rest operator with array destructuring for getting first and second element separately and rest of the elements in a separate array.

    let arr =[1,2,3,4,5];let[first, second,...rest]= arr;
    
    console.log(first);// 1
    console.log(second);// 2
    console.log(rest);// [3, 4, 5]

    Output

    1
    2
    [3, 4, 5]
    

    Rest Operator with Object Destructuring

    Now, if you want specific properties separately and rest of the properties in a separate object, you can use rest operator for achieving that. Rest operator also help us to destructure an object.

    Code-Snippet

    Below is an example snippet of using rest operator with object destructuring for having first and second property separately and rest of the properties in a separate object.

    let obj ={ name:"Aish", age:21, city:"Hyderabad", country:"India"};let{ name, age,...rest }= obj;
    
    console.log(name);//  Aish
    console.log(age);// 21
    console.log(rest);// { city: "Hyderabad", country: "India" }

    Output

    Aish
    21
    { city: "Hyderabad", country: "India" }
  • Reduce Method

    What is Reduce Method?

    In JavaScript, Reduce method is used to manipulate array. This method executes a reducer function on each element of the array (from left to right) and returns a ‘single value’ as a result.

    It accepts an optional parameter named ‘initialValue’. If we do not pass this parameter to the method, it will consider the arr[0] value as the initial value. Additionally, it will execute the callback function on the passed initialValue parameter.

    This method does not execute the reducer function for empty array elements. In addition to that, it does not modify the original array.

    Note : If the current array is empty or doesn’t contain any initialValue, this method will throw a ‘TypeError’ exception.

    Syntax

    Following is the syntax of JavaScript Array.reduce() method

    reduce(callbackFn(accumulator, currentValue, currentIndex, array), initialValue)

    Parameters

    The reduce() function has two parameters which are callbackfn() and initialValue. They are described below in detail.

    • initialValue (optional): The value to which the accumulator parameter is initialized when the first time the callback function is called.
    • callbackFn: This is the function that executes on each element in the array.

    The callbackFn() function in turn takes four arguments They are –

    • accumulator: This is the current element being processed in the array. If the initialValue is specified, its value will be arr[0], if not its value will be arr[1].
    • currentValue: It refers to the current element.
    • currentIndex (optional): This is the index of the current element being processed in the array.
    • array (optional): This is the array on which the reduce() method is called.

    Return Value

    This method returns the single value that is the result after reducing the array.

    Example

    In the following example, we are using the JavaScript Array.reduce() method to sum all the elements present in the provided array.

    <html><body><script>const number =[10,20,30,40,50];const sum = number.reduce((accumulator, currentValue)=> accumulator + currentValue,0);
    document.write(sum);</script></body></html>

    The accumulator starts at 0, and for each element in the array, it adds the current element to the accumulator. The final result of the accumulator (150) is the sum of all the elements.

    Output

    Following is the output of the above code

    150
    

    Example

    If the current array does not contain any element(no initial value available), the reduce() method will throw a “TypeError” exception

    <html><body><script>const numbers =[];try{
    
      numbers.reduce((accumulator, currentValue)=&gt; accumulator * currentValue);}catch(error){
      document.write(error);}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Following is the output of the above code

    TypeError: Reduce of empty array with no initial value
    

    Reduce method on TypedArray

    We can use reduce method on TypedArray as well. Everything is similar to normal array, means we can process and combine elements in same way as we do with arrays.

    Syntax

    Following is the syntax of JavaScript TypedArray reduce() method

    TypedArray.reduce(callbackFn(accumulator, currentValue, currentIndex, array), initialValue)

    Example

    The product of all elements within a typed array.

    In the following example, we are using the JavaScript TypedArray reduce() method to execute the user-provided function named multi() on each element of this typed array [1, 2, 3, 4, 5]. The multi() function multiplies all the elements within the current typed array.

    <html><head>
    JavaScript TypedArray reduce() Method
    </head><body><script>//functionfunctionmulti(accumulator, currentValue){return accumulator * currentValue;}const T_array =newUint16Array([1,2,3,4,5]);
    document.write("Typed array: ", T_array);//Using the reduce() method
    document.write("<br>The product of typed array elements: ", T_array.reduce(multi));</script></body></html>

    Output

    Following is the output of the above code

    Typed array: 1,2,3,4,5
    The product of typed array elements: 120
    

    Example

    If the current typed array does not contain any element(no initial value available), the reduce() method will throw a "TypeError" exception.

    In the given example below, we use the JavaScript TypedArray reduce() method to execute the user-provided reducer callback function named "ArrowFunction" on each element of this empty typed array ([]).

    <html><head><title>JavaScript TypedArray reduce() Method</title></head><body><script>const T2_array =newUint16Array([]);//empty typed array
    document.write("Length of the typed array: ", T2_array.length);//using the reduce methodtry{
       T2_array.reduce((a, b)=> a + b);}catch(error){
    
    document.write("&lt;br&gt;", error);}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Following is the output of the above code

    Length of the typed array: 0
    TypeError: Reduce of empty array with no initial value
    

    Reduce method on Map

    We can use reduce method on Map as well. Everything is similar to normal array, means we can process and combine elements in same way as we do with arrays.

    Syntax

    Following is the syntax of JavaScript Map reduce() method

    Map.reduce(callbackFn(accumulator, currentValue, currentIndex, array), initialValue)

    Example

    The sum of all elements within a Map.

    In the following example, we are using the JavaScript Map reduce() method to execute the user-provided function named add() on each element of this map. The add() function adds all the elements within the current map.

    <html><head><title>JavaScript Map reduce() Method</title></head><body><script>//functionfunctionadd(accumulator, currentValue){return accumulator + currentValue;}const map =newMap([[1,2],[3,4],[5,6]]);
    document.write("Map: ", map);//using the reduce() method
    document.write("<br>The sum of map elements: ",[...map.values()].reduce(add));</script></body></html>

    Output

    Following is the output of the above code

    Map: 1 => 2,3 => 4,5 => 6
    The sum of map elements: 12
  • Reactive Programming

    Reactive Programming is basically a way to write code that makes it easier to deal with things happens over timelike data coming from a network, users clicking on stuff, or updates popping up in a database. In reactive programming, we look at data as a stream of events. So instead of just waiting a lot for data to be ready, were kind of subscribe to these events and responding as soon as they happen.

    Working with async (asynchronous) data gets a lot simpler with reactive programming. Async data can usually be tough because we dont know exactly when it will show up. But here in reactive programming, everything acts like a stream; we just listen for the data and handle it as soon as its ready.

    Secondly, the reactive programming can actually make our code faster, because we get notified exact the moment new data comes in. We dont have to keep checking for it; it just shows up when its ready, and this makes a lot easier for us.

    Lastly, this makes our code more understandable and manageable. because were handling data as a flow of events, its clear how the different pieces of code connect with each other. The code becomes more declarative, we just say what should happen, and it takes care of reacting to events in the right order. So its not only efficient but also keeps things cleaner and easier to work.

    Reactive Programming in JavaScript

    There are several libraries and frameworks that help us write reactive code in JavaScript. Some of the most popular ones are:

    • RxJS: RxJS is a JavaScript library that gives tools for reactive programming. It is a popular framework, It is also used a lot with frameworks like Angular, and you may also have seen used with React. RxJS lets us handle data as a stream of events, that makes it much simple to deal with async stufflike user actions, API calls, or real-time updates.
    • React: React is a JavaScript library mostly for building user interfaces. The great part is if data changes behind the scenes, React just updates the UI for us. React uses a virtual DOM which is a simple version of the actual webpage so it only updates the specific parts of the page, instead of updating whole webpage each time. This makes things faster as less time needed to update some of components.
    • Vue.js: Vue.js is also a JavaScript framework for building user interfaces, and its designed to grow along with your project. It has a reactive data model, meaning if the data changes, the UI automatically changes. Vue has handy tools like computed properties (which handle data that depends on other data) and watchers (which track changes and let us react to them right away). This makes Vue pretty straightforward and really useful for building interactive features.
  • Prototype

    Prototype is like a template in JavaScript. These template help object to share the properties and methods. Instead of duplicating code everywhere, we can define method or property once and then can easily share with other instances of an object.

    Types of Prototype in JavaScript

    In JavaScript, there are more than one type of prototype that are used to share the properties and methods among the objects. The main types of prototype in JavaScript are:

    • Object Prototype
    • Constructor Function Prototype
    • Function Prototype
    • Built-in Prototype

    Object Prototype

    The object prototype is foundational template to all objects in JavaScript. This template is available in every object we create by default. It is like built-in sheet of tool that every object can use.

    Code Snippet

    Following is an example snippet of using object prototype.

    let obj ={
       name:"John",
       age:21};
    console.log(obj);
    console.log(obj.toString());// [object Object]

    Output

    Following is the output of above code snippet −

    { name: 'Ansh', age: 24 }
    

    In above example, we have created an object named obj with properties name and age. We also have used toString() method which is available by default in object prototype.

    Constructor Function Prototype

    A construction function is type of function that is used for creating new objects. When we need to create multiple objects having same properties and behaviours, we can use constructor function. Constructor function prototype is used to share the properties and methods among the objects created using constructor function.

    Code Snippet

    Below is an example snippet of using constructor function prototype.

    functionPerson(name, age){this.name = name;this.age = age;}Person.prototype.greet=function(){return"Hello, "+this.name;}let person1 =newPerson("John",21);let person2 =newPerson("Ansh",24);

    Output

    Following is the output of above code snippet.

    Hello, John
    Hello, Ansh
    

    In above example, we have created a constructor function named Person. We also have added a method greet to the prototype of Person. We have created two objects person1 and person2 using Person constructor function and then called greet method on both objects.

    Function Prototype

    Function prototype is a template that is available to all functions in JavaScript. This template is used to share the properties and methods among the functions.

    Code Snippet

    Below is an example snippet of using function prototype.

    functiongreet(){return"Hello, World!";}
    console.log(greet.toString());// function greet() { return "Hello, World!"; }

    Output

    Following is the output of above code snippet.

    function greet() { return "Hello, World!"; }
    

    In above example, we have created a function named greet. We also have used toString() method which is available by default in function prototype.

    Built-in Prototype

    There are many built-in objects in JavaScript like Array, String, Number, etc. These built-in objects have their own prototype. We can use these prototypes to share the properties and methods among the objects of these built-in objects.

    Code Snippet

    Below is an example snippet of using built-in prototype.

    let arr =[1,2,3,4,5];
    
    console.log(arr);
    console.log(arr.toString());// 1,2,3,4,5
    console.log(arr.join("-"));// 1-2-3-4-5
    console.log(arr.reverse());// [ 5, 4, 3, 2, 1 ]

    Output

    [ 1, 2, 3, 4, 5 ]
    1,2,3,4,5
    1-2-3-4-5
    [ 5, 4, 3, 2, 1 ]
    

    In above example, we have created an array named arr. We also have used toString()join(), and reverse() methods which are available by default in array prototype.

  • Parameters vs Arguments

    Parameters and arguments are terms that are used for the function. Both are generally confused with each other. But they are different from each other in JavaScript. In this tutorial, we will learn about the difference between parameters and arguments in JavaScript.

    Parameters

    Parameters are variable names that are used in the function definition. They are used to hold the values of the arguments that are passed to the function.

    Arguments

    Arguments are used in the function call. These are the values that are passed to the function when it is called. They are the actual values that are passed to the function when it is called.

    We can pass any number of arguments to the function. But the number of arguments should match the number of parameters in the function definition. If the number of arguments is less than the number of parameters, the remaining parameters will be undefined. If the number of arguments is more than the number of parameters, the extra arguments will be ignored.

    Parameters vs Arguments

    Following are the notable Differences Between Parameters and Arguments −

    ParametersArguments
    Parameters are the variable names that are used in the function definition.Arguments are the real values that we need to pass to the function when it is called.
    Parameters are used to hold the values of the arguments that are passed to the function.Arguments are the values that are passed to the function when it is called.
    Parameters are used in the function definition.Arguments are used in the function call.

    Example

    Lets see an example −

    <html><body><script>functionadd(a, b){return a + b;}
    document.write(add(10,20));</script></body>

    Output

    30
    

    Explanation

    In the above example, there is a function called add() that adds up the two numbers. In the function definition, there are two parameters a and b. When the function is called, the values 10 and 20 are passed as arguments to the function. These values are stored in the parameters a and b. The function returns the sum of these two values.