Blog

  • JavaScript – Document Object Model or DOM

    The HTML DOM allows JavaScript to access and modify the content of HTML elements. JavaScript can change all HTML elements, attributes, CSS styles in the page. JavaScript can also add, remove the HTML elements and attributes. Using JavaScript, we can even create new events in the page.

    Every web page resides inside a browser window which can be considered as an object.

    A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content.

    What is DOM?

    The DOM is an acronym for the Document Object Model. It is a programming interface for Core, XML, and HTML DOM.

    It is a W3C (World Wide Web Consortium) standard.

    The DOM defines the logical or tree-like structure of the web page or document. In the tree, each branch ends in a node, and each node contains objects. DOM methods allow us programmatic access to the tree. Using the DOM methods, you can change the document’s structure, content or style.

    What is HTML DOM?

    HTML creates the web page’s structure, and JavaScript adds interaction to the web page by manipulating the HTML elements.

    JavaScript cant interact directly with HTML elements. So, whenever a web page loads in the browser, it creates a DOM.

    So, the document object represents the HTML document displayed in that window. Furthermore, each iframe in the webpage creates a new DOM. The Document object has various properties that refer to other objects that allow access to and modify document content.

    The way a document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document.

    • Window object − It represents the current window of the browser. It also works as a global object for the browser window. It is at the top of the hierarchy. It is the outmost element of the object hierarchy.
    • Document object − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page. It is used to access and modify the elements of the web page.
    • Form object − Everything enclosed in the <form>…</form> tags sets the form object.
    • Form control elements − The form object contains all the elements defined for that object, such as text fields, buttons, radio buttons, and checkboxes.

    Here is a simple hierarchy of a few important objects −

    HTML DOM

    There are several DOMs in existence. The following sections explain each of these DOMs in detail and describe how you can use them to access and modify document content.

    • The Legacy DOM − This is the model which was introduced in early versions of JavaScript language. It is well supported by all browsers, but allows access only to certain key portions of documents, such as forms, form elements, and images.
    • The W3C DOM − This document object model allows access and modification of all document content and is standardized by the World Wide Web Consortium (W3C). This model is supported by almost all the modern browsers.

    There are three different types of the DOM according to the W3C.

    • Core DOM − It is a standard model for all document types.
    • HTML DOM − It is a standard model for HTML documents.
    • XML DOM − It is a standard model for XML documents.

    Why is DOM required?

    As discussed above, when a web page is loaded into the browser window, it becomes a document object.

    After that, JavaScript can access the HTML elements and perform the other operations on them. It means JavaScript can interact with the web page using the HTML DOM.

    For example, JavaScript can perform the below operations on HTML elements using the document object.

    • Access HTML elements
    • Replace HTML elements
    • Add New HTML elements
    • Delete HTML elements
    • Change CSS of HTML elements
    • Change attributes of HTML elements
    • Add animation to HTML elements
    • Add events to HTML elements

    However, there are other uses of the document object, which we will cover in upcoming chapters.

    DOM Interfaces

    The DOM interfaces are the actual components of the DOM that work with JavaScript or any other programming language to manipulate the web page. They provide various methods and properties to interact with and manipulate web pages.

    List of the DOM interfaces is −

  • JavaScript – var Keyword

    The var keyword in JavaScript is used to declare variables. Before ES6, there was only var keyword to declare a variable. In ES6, let and const keywords were introduced as a better way to declare variables. It is advised to use let instead of var to declare a variable. If you are targeting older version of browser, you can use var.

    In JavaScript, variables are the data storage container. You can use the variables to store any type of data. For example, string, number, boolean, object, etc.

    A variable declared with var keyword has function scope. Whereas a variable declared with let has block scope.

    Syntax

    Follow the syntax below to define the variable using the ‘var’ keyword.

    var identifier;var identifier = value;

    Here, the identifier can be a valid variable name. In the JavaScript – Variables chapter, we have already discussed the rules to define valid identifiers.

    You may assign or not value to the variable while declaring it using the JavaScript ‘var’ keyword.

    Example

    In the below code, we have defined the 3 variables using the ‘var’ keyword. In the num1 variable, we have stored the numeric value. In the str1 variable, we have stored the string value; in the bool variable, we have stored the boolean value.

    <html><body><div id ="output1"></div><div id ="output2"></div><div id ="output3"></div><script>var num1 =30;var str1 ="Hello World!";var bool =true;
          document.getElementById('output1').innerHTML = num1;
          document.getElementById('output2').innerHTML = str1;
          document.getElementById('output3').innerHTML = bool;</script></body></html>

    Output

    30
    Hello World!
    true
    

    JavaScript Variable Scopes

    The scope of the variable defined using the JavaScript ‘var’ keyword has a function scope or global scope.

    JavaScript Function Scope

    When you define the variable inside the function using the var keyword, it can be accessible inside the function anywhere. Even if you define the variable using the var keyword inside the particular block inside the function, it can be accessible anywhere.

    Let’s understand the function scope with the example below.

    Example

    In the below code, we have defined the variable ‘x’ inside the function. We have also defined the variable ‘y’ inside the block, which is inside the function.

    After that, we access the variables x and y inside the function.

    <html><body><div id ="demo1"></div><div id ="demo2"></div><script>functiondemo(){var x =10;{var y =20;// x and y both can be accessible here}
             document.getElementById('demo1').innerHTML ="X == "+ x;
             document.getElementById('demo2').innerHTML ="Y == "+ y;}demo();</script></body></html>

    Output

    X == 10
    Y == 20
    

    If you define the variable using the let keyword inside the block, which is inside the function, and try to access it outside the block, it will throw an error.

    JavaScript Global Scope

    It becomes the global variable if you define the variable using the ‘var’ keyword outside the function or a particular block.

    After that, you can access the variable anywhere inside the code using the window object.

    Example

    We have defined the ‘num1’ global variable in the code below.

    After that, we access the ‘num1’ variable inside the function using and without using the window object.

    <html><body><div id ="output"></div><script>const output = document.getElementById('output');var num1 =10;functionsum(num2){
             output.innerHTML +="num1 + num2 = "+(num1 + num2)+"<br>";
             output.innerHTML +="window.num1 + num2 = "+(window.num1 + num2);}sum(20);</script></body></html>

    Output

    num1 + num2 = 30
    window.num1 + num2 = 30
    

    JavaScript Variable Hoisting

    The variable defined using the ‘var’ keyword is hoisted at the top of its scope. It means JavaScript adds the declaration of the variable at the top of its scope.

    So you can access the variable before the declaration of the variable.

    Example

    In the below code, we have initialized the variable ‘a’ and printed its value before its declaration.

    The code runs without error, as the variable defined using the var keyword is hoisted at the top of its scope.

    <html><body><div id ="output">Value of the variable a is:</div><script>functioncheckHoisting(){
             a =98;
             document.getElementById('output').innerHTML += a;var a;}// You can't access the variable a here.checkHoisting();</script></body></html>

    Output

    Value of the variable a is: 98
    

    The above JavaScript code is similar to the below code.

    var a;
    a =98;
    document.getElementById('output').innerHTML += a;

    Redeclaration of variable defined using the ‘var’ keyword

    You can redeclare the variables using the ‘var’ keyword, and the code will run without any error.

    If you have initialized the last duplicate variable with the latest value, it will contain that value. But if you don’t initialize the last duplicate variable, the variable will contain its previous value without losing it.

    Example

    In the code below, we have defined the variable ‘a’ two times and initialized it with different values. You can observe in the output that variable ‘a’ contains the last value.

    We have defined the variable ‘a’ a third time and haven’t initialized it. So, it contains the value of the 2nd ‘a’ variable.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');var a =10;var a =20;
          output.innerHTML +="The value of the a is: "+ a +"<br>";var a;
          output.innerHTML +="The value of the a is: "+ a;</script></body></html>

    Output

    The value of the a is: 20
    The value of the a is: 20
    

    If you define the duplicate variables in the different scopes, it can have value according to where you access the variable.

    Example

    In the code below, we have defined the ‘num’ variable outside and inside the function. When you access it inside or outside the function, it prints the different values.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');var num =10;functionprintNum(){var num =20;
             output.innerHTML +="Num inside the function is: "+ num +"<br>";}printNum();
          output.innerHTML +="Num outside the function is: "+ num +"<br>";</script></body></html>

    Output

    Num inside the function is: 20
    Num outside the function is: 10
    

    Declaring Many Variables in a Single Statement

    If you want to declare multiple variables using the JavaScript ‘var’ keyword, you can declare all variables in a single statement. It makes code readable.

    Example

    In the below code, we have declared the variables ‘a’ and ‘b’ in the single statement and initialized them with different values after declaring.

    <html><body><div id ="output1"></div><div id ="output2"></div><script>var a, b;
          a =70;
          b =80;
          document.getElementById('output1').innerHTML ="The value of a is: "+ a;
          document.getElementById('output2').innerHTML ="The value of b is: "+ b;</script></body></html>

    Output

    The value of a is: 70
    The value of b is: 80
    

    However, you can also assign the values to the variables while declaring the multiple variables in a single statement.

    Using the var keyword with loops

    When you use the JavaScript ‘var’ keyword to define the iterator variable of for loop, you can also access it outside the for loop.

    Example

    In the below code, we have defined the variable ‘p’ inside the for loop. We access the variable p inside and outside the loop.

    <html><body><div id ="output"></div><script>const output = document.getElementById('output');for(var p =0; p <5; p++){
             output.innerHTML +="The value of p is: "+ p +"<br>";}
          output.innerHTML +="The value of p outside the loop is: "+ p;</script></body></html>

    Output

    The value of p is: 0
    The value of p is: 1
    The value of p is: 2
    The value of p is: 3
    The value of p is: 4
    The value of p outside the loop is: 5
    

    Declaration with Destructuring

    In JavaScript, you can declare the variables using the ‘var’ keyword while destructuring the array or objects.

    Example

    In the below code, the ‘arr’ array contains 3 variables.

    After that, we define variables using the ‘var’ keyword and destructure the array.

    <html><body><div id ="output"></div><script>const output = document.getElementById('output');var arr =[4,5,6];var[a, b, c]= arr;
          output.innerHTML ="a = "+ a +", b = "+ b +", c = "+ c;</script></body></html>

    Output

    a = 4, b = 5, c = 6
    

    You can also use the ‘var’ keyword to define the variables and store the objects or function expressions.

  • JavaScript – new Keyword

    The new keyword in JavaScript is used to create an instance of the object that has constructor function. Using new keyword, we can create the instances of a user-defined as well as built-in object types. We can create instances of the classes, prototype, or constructor functions.

    When a JavaScript function is called with new keyword, the function is used as constructor. The new keyword will do the following:

    • Creates a blank/ empty JavaScript object.
    • Sets its prototype for inheritance.
    • Binds this variable internally with newly created object.
    • Executes the constructor function using new crated object whenever this is used.
    • Returns newly created object, unless the contractor function returns a non-null object reference.

    The new keyword is also used to create an instance of the built-in JavaScript objects like String, Boolean, Number, etc.

    Syntax

    The syntax to use the new keyword in JavaScript is as follows

    newConstructor(arguments);

    Parameters

    • Constructor − It is the name of the constructor function or class name.
    • arguments −It can be multiple arguments to initialize the object properties with them.

    Return Value

    • It returns the newly created object if the constructor function returns nothing or a primitive value.
    • It returns the value that is returned by constructor function if constructor returns a non-primitive value.

    Using ‘new’ keyword with Function Constructor

    To use a function as a constructor, we should call the function with new keyword placing it before the function name.

    We can define multiple objects using function constructor. The function constructor works as the object’s prototype.

    Follow the syntax below to use the ‘new’ keyword and constructor function to define the object.

    newFuncName(arguments);

    Example

    We have defined the Watch() constructor function in the code below.

    The Watch() constructor function initializes the brand, price, and type properties.

    After that, we have created two new instances of the Watch() function and printed them in the output.

    <html><body><div id ="output"></div><script>functionWatch(brand, price, type){this.brand = brand;this.price = price;this.type = type;}const titan =newWatch('titen',4000,'analog');const sonata =newWatch('sonata',3000,'digital');
       document.getElementById('output').innerHTML +="The titan object is: "+JSON.stringify(titan)+"<br>"+"The sonata object is: "+JSON.stringify(sonata);</script></body></html>

    Output

    The titan object is: {"brand":"titen","price":4000,"type":"analog"}
    The sonata object is: {"brand":"sonata","price":3000,"type":"digital"}
    

    Example

    In the below code, we have defined the Laptop() constructor function, initializing various properties related to the laptop. Also, we have defined the getLaptop() function, which prints the laptop details.

    After that, we created the two instances of the Laptop() object and used the getLaptop() method with both. In this way, you can share single methods with different objects.

    <html><body><div id ="output"></div><script>const output = document.getElementById('output');functionLaptop(brand, model, processor){this.brand = brand;this.model = model;this.processor = processor;this.getLaptop=function(){
    	     output.innerHTML +=this.brand +", "+this.model +", "+this.processor +"<br>";}}constHP=newLaptop('HP',"VIKING","i7");const Dell =newLaptop('Dell',"Inspiron","i5");HP.getLaptop();
       Dell.getLaptop();</script></body></html>

    Output

    HP, VIKING, i7
    Dell, Inspiron, i5
    

    Using ‘new’ keyword with Class

    You can also use the new keyword to define the instance of a class. The class also provides the blueprint for the object.

    Before ES6, the constructor function was used to define the template for the object. After ES6, classes are used to define the template for the object.

    Example

    In the below example, we have defined the ‘WindowClass class. In the ‘WindowClass’ we have added the constructor to initialize the properties. We have also added the getDetails() method in the class.

    After that, we used the ‘new’ keyword followed by the class name to define an object of the WindowClass.

    Next, we invoke the getDetails() method on the instance of the class.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo')classWindowClass{constructor(color, size, type){this.color = color;this.size = size;this.type = type;}getDetails=function(){
                output.innerHTML ="Color: "+this.color +"<br>"+"Size: "+this.size +"<br>"+"Type: "+this.type;}}// Creating the instance of WindowClass classconst window1 =newWindowClass('blue','small','wooden');// Calling function object
          window1.getDetails();</script></body></html>

    Output

    Color: blue
    Size: small
    Type: wooden
    

    Using ‘new’ keyword with built-in object

    You can also use the ‘new’ keyword to define the instance of the built-in object having constructor functions.

    Follow the syntax below to create an instance of the built-in object Number.

    const num =newNumber(10);

    In the above syntax, we have passed the numeric value as an argument of the Number() constructor.

    Example

    In the code below, we have used the Number() and String() constructors with a new keyword to define the numeric and string objects.

    After that, we used the ‘typeof’ operator to check the type of num and str variables. In the output, you can see that the num and str variable type is an object.

    <html><body><div id ="output"></div><script>const num =newNumber(10);const str =newString("Hello");
          document.getElementById("output").innerHTML ="num = "+ num +", typeof num "+typeof num +"<br>"+"str = "+ str +", typeof str "+typeof str;</script></body></html>

    Output

    num = 10, typeof num object
    str = Hello, typeof str object
  • JavaScript – void Keyword

    The void keyword in JavaScript is used as an operator that evaluates a given expression and returns undefined. The void is an important keyword in JavaScript. The meaning of the void is null or empty.

    The void keyword can be used as a unary operator that appears before its single operand, which may be of any type. This operator specifies an expression to be evaluated without returning a value or returning the undefined.

    Syntax

    The syntax to use the void keyword in JavaScript −

    void operand;

    In the above syntax, the operand can be any expression.

    Return Value

    It returns the undefined.

    Example

    In the below code, we used the 10 with the ‘void’ keyword. In the output, you can observe that it returns undefined.

    <html><body><div id ="output">The value of the ans variable is:</div><script>let ans =void10;
          document.getElementById("output").innerHTML += ans;</script></body></html>

    Output

    The value of the ans variable is: undefined
    

    Importance of Precedence of void Keyword

    Generally, the JavaScript ‘void’ keyword is used to return the primitive undefined value, but if you don’t take precedence in the consideration, it can return a different value.

    Let’s understand it via the example below.

    Example

    In the below code, the void operator takes precedence over the strict equality operator in the first expression. So, it first evaluates ‘void 10’ to undefined and compares it with 20. So, it returns false.

    The second expression evaluates ’10 === 20′ first to false and evaluates ‘void false’ to undefined.

    <html><body><div id ="output1"></div><div id ="output2"></div><script>let res1 =void10===20;let res2 =void(10===20);
          document.getElementById("output1").innerHTML += res1;
          document.getElementById("output2").innerHTML += res2;</script></body></html>

    Output

    false
    undefined
    

    What is javascript:void(0)?

    Let’s break down the javascript:void(0) into two parts and understand both separately.

    javascript:

    You can use the ‘javascript:’ to create a pseudo URL. Using ‘javascript:’ you can create the interactive URL.

    You need to write the expression after ‘javascript:’, and when users click the anchor text, it executes the JavaScript code.

    Let’s understand it via the example below.

    Example

    In the below code, we have created the link text and used the JavaScript URL as a href. When you click the anchor text, it writes it in the HTML document.

    <html><body><a href ="javascript:document.write('Anchor text is clicked!')"> Click me!</a></body></html>

    In this way, you can use the ‘javascript:uri’ to create the pseudo URL.

    void(0)

    The void(0) evaluates the JavaScript expression, but it returns undefined. So, when you want to execute the expression without performing any action, you can use the void(0).

    javascript: void(0)

    When you don’t want to navigate users to another web page when they click on the link, you can use the ‘javascript:void(0)’ as a href value of the anchor tag.

    Let’s understand it via the example below.

    Example

    It won’t do anything Whenever you click the anchor text in the code below.

    <html><body><a href ="javascript:void(0)"> Click me!</a></body></html>

    You can also use the ‘javascript:void(0)’ when you want to update the web page using the URI but don’t want to navigate to another web page.

    Example

    In the below code, when you click the anchor text, it will change the background color of the body, rather than navigating to another web page.

    <html><body><a href ="javascript:void(0);" 
       	  onclick ="document.body.style.backgroundColor = 'blue'"> 
       	  Change Background Color 
       </a></body></html>

    The void Keyword with Functions

    When you use the void keyword with JavaScript functions, it returns undefined. After that, if you try to execute the function, it will throw an error, as the ‘void’ operator considers the function as its operand and evaluates it as undefined.

    Example

    In the below code, we have defined the test() function and used the ‘void’ keyword with it.

    Also, used the trycatch block to catch the error.

    In the try block, we execute the function, and in the output, you can observe that control goes into the catch block.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');try{voidfunctiontest(){
             output.innerHTML +="The test function is executed!";}test();}catch(error){
          output.innerHTML +="The test function is undefined!";}</script></body></html>

    Output

    The test function is undefined!
    

    The void Keyword with Immediately Invoked Function

    When you use the ‘void’ keyword with the JavaScript immediately invoked function, it invokes the function expression first and evaluates it as undefined.

    Example

    In the below code, we have defined the immediately invoked function with the void keyword. You can observe that it invokes the function first and returns undefined.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");voidfunction(){
             output.innerHTML ="Unknown function is executed!";}();</script></body></html>

    Output

    Unknown function is executed!
    

    Also, you can use the ‘void’ keyword with the arrow function to return undefined from the arrow function. The JavaScript:void() URI can also be used to prevent the web page reloading by default, like the preventDefault() method.

  • JavaScript – this Keyword

    What is ‘this’ keyword?

    In JavaScript, the ‘this‘ keyword contains the reference to the object. It represents the context of the function or current code. It is used to access the properties and methods of the current object.

    When this keyword is used inside a function, the this will refer to the object that the function is called with.

    In JavaScript, functions are also objects. So, you can use the ‘this’ keyword with functions also.

    Which object does the ‘this’ refer to?

    The object referred by the ‘this‘ keyword depends on how you have used the ‘this’ keyword.

    For example,

    • The ‘this’ keyword refers to the window object in the global scope.
    • When you use the ‘this’ keyword inside the function, it also represents the ‘window’ object.
    • The ‘this’ keyword refers to an undefined in the strict mode in the function.
    • The ‘this’ keyword refers to the object when you use it in the object method.
    • In the event handler, the ‘this‘ keyword refers to the element on which the event is executed.
    • The ‘this’ keyword in methods like call(), apply(), and bind() can refer to different objects.

    Syntax

    Follow the syntax below to use the ‘this’ keyword in JavaScript &minus

    this.property
    ORthis.method();

    You can access the properties and execute the object’s methods using the ‘this’ keyword.

    JavaScript ‘this’ in the Global Scope

    When you use the ‘this’ keyword in the global scope, it represents the global (window) object. You can access the global variables using the ‘this’ keyword in the global scope.

    Example

    In the below code, we have defined the ‘num’ variable and printNum() function in the global scope. After that, we used the ‘this’ keyword to access the global variable and functions.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');var num =10;functionprintNum(){
             output.innerHTML +="Inside the function: "+ num +"<br>";}this.printNum();
          output.innerHTML +="Outside the function: "+this.num +"<br>";</script></body></html>

    Output

    Inside the function: 10
    Outside the function: 10
    

    JavaScript ‘this’ in a Function

    When you use the ‘this’ keyword in the function, it represents the global scope or ‘window’ object.

    Example

    In the below code, we use the ‘this’ keyword inside the function. You can observe that we access the global variables using the ‘this’ keyword inside the function.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');var message ="Hello World!";functionprintMessage(){var message ="Hi! How are you?";
             output.innerHTML ="The messsage is: "+this.message;}printMessage();</script></body></html>

    Output

    The messsage is: Hello World!
    

    ‘this’ in a Function in Strict Mode

    When you use the ‘this’ keyword inside the function in the strict mode, it doesn’t refer to any object. The value of the ‘this’ keyword becomes undefined.

    Example

    In the below code, we use the ‘this’ keyword inside the function in the strict mode. It prints undefined.

    <html><body><div id ="demo"></div><script>let output = document.getElementById('demo');var message ="Hello World!";functiontest(){"use strict";
             output.innerHTML ="The value of this in the strict mode is: "+this;}test();</script></body></html>

    Output

    The value of this in the strict mode is: undefined
    

    ‘this’ in a Constructor Function

    When you use the function as a constructor function to create an object, the ‘this’ keyword refers to the object.

    Example

    We have defined the Animal() constructor function in the code below. We used the ‘this’ keyword inside the constructor function to initialize the properties of the object.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');functionAnimal(){this.name ='Lion';this.age =3;this.color ='Brown';}const newAnimal =newAnimal();
          output.innerHTML ="Animal Name: "+ newAnimal.name +"<br>";
          output.innerHTML +="Animal Age: "+ newAnimal.age +"<br>";
          output.innerHTML +="Animal Color: "+ newAnimal.color;</script></body></html>

    Output

    Animal Name: Lion
    Animal Age: 3
    Animal Color: Brown
    

    ‘this’ in an Arrow Function

    When you use the ‘this’ keyword in the arrow function, it refers to the scope of its parent object.

    For example, when you define the arrow function inside the object method and use the ‘this’ keyword inside that, it presents the object. The ‘this’ keyword refers to the global object if you define the arrow function inside another function.

    Example

    In the below code, we have defined the arrow function inside the getDetails() method of the object. When we print the value of the ‘this’ keyword, it prints the object.

    <html><body><div id ="output1">Value of'this' inside the getDetails() method:</div><div id ="output2">Value of'this' inside the getInnerDetails() method:</div><script>const wall ={
    		 size:"10",
    		 color:"blue",getDetails(){
    		    document.getElementById('output1').innerHTML +=JSON.stringify(this);constgetInnerDetails=()=>{
    			   document.getElementById('output2').innerHTML +=JSON.stringify(this);}getInnerDetails();}}
          wall.getDetails();</script></body></html>

    Output

    Value of 'this' inside the getDetails() method: {"size":"10","color":"blue"}
    Value of 'this' inside the getInnerDetails() method: {"size":"10","color":"blue"}
    

    ‘this’ in the Object Method

    When you use the ‘this’ keyword inside the object method, it represents the object itself.

    Example

    In the below code, we have defined the ‘fruit; object. The object contains the printFruitDetails() method, and in the method, we used the ‘this’ keyword to access the properties of the object.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');const fruit ={
             name:"Apple",
             color:"red",printFruitDetails(){
                output.innerHTML +="Furit Name = "+this.name +"<br>";
                output.innerHTML +="Fruit Color = "+this.color;}}
          fruit.printFruitDetails();</script></body></html>

    Output

    Furit Name = Apple
    Fruit Color = red
    

    ‘this’ in a Child Function of an Object Method

    When you define the function inside the object method and use the ‘this’ keyword inside the function, it represents the global object rather than an object.

    Example:

    In the below code, we have defined the person object. The person object contains the printDetails() method. In the printDetails() method, we have defined the printThis() function.

    In the printThis() function, we print the value of the ‘this’ keyword, and it prints the global object.

    <html><body><div id ="output">Inside the printThis()function, Value of'this'=</div><script>const person ={
          name:"Salman",
          isBusinessman:false,printDetails(){functionprintThis(){
                document.getElementById('output').innerHTML +=this;}printThis();}}
       person.printDetails();</script></body></html>

    Output

    Inside the printThis() function, Value of 'this' = [object Window]
    

    JavaScript ‘this’ in Event Handlers

    Using the ‘this’ keyword with event handlers refers to the HTML element on which the event is executed.

    Example

    In the below code, we have added the onClick event handler into the <div> element. When users click the div element, we hide the div element using the ‘display’ property.

    <html><head><style>
          div {
            height:200px;
            width:700px;
            background-color: red;}</style></head><body><p>Click the DIV below to remove it.</p><div onclick ="this.style.display = 'none'"></div></body></html>

    Explicit Function Binding in JavaScript

    In JavaScript, call(), apply(), or bind() methods are used for the explicit binding.

    The explicit binding allows you to borrow the method of the particular object. Using these methods, you can explicitly define the context of the ‘this’ keyword.

    Let’s understand explicit binding using the examples below.

    Example: Using the call() method

    In the below code, the lion object contains the color and age property. It also contains the printDetails() method and prints the details using the ‘this’ keyword.

    The tiger object contains only color and age properties. We used the call() method to call the printDetails() method of the lion object with the context of the tiger object. So, the method prints the details of the tiger in the output.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');const lion ={
        color:"Yellow",
        age:10,printDetails(){
          output.innerHTML +=`<p>Color: ${this.color}</p>`;
          output.innerHTML +=`<p>Age: ${this.age}</p>`;}}const tiger ={
        color:"Orange",
        age:15,}
      lion.printDetails.call(tiger);</script></body></html>

    Output

    Color: Orange
    
    Age: 15
    

    Example: Using the bind() method

    The below code also contains the lion and tiger objects. After that, we used the bind() method to bind the printDetails() method of the lion object into the tiger object.

    After that, we use the tigerDetails() method to print the details of the tiger object.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');const lion ={
        color:"Yellow",
        age:10,printDetails(){
          output.innerHTML +=`<p>Color: ${this.color}</p>`;
          output.innerHTML +=`<p>Age: ${this.age}</p>`;}}const tiger ={
        color:"Orange",
        age:15,}const tigerDetails = lion.printDetails.bind(tiger);tigerDetails();</script></body></html>

    Output

    Color: Orange
    
    Age: 15
    

    JavaScript ‘this’ Precedence

    You should use the below precedence order to determine the context of the ‘this’ keyword.

    • 1. bind() method
    • 2. call and apply() methods
    • 3. Object method
    • 4. Global scope
  • JavaScript – Extending Errors

    The custom errors in JavaScript are errors that you create yourself, as opposed to the built-in errors that JavaScript throws. You can create custom errors to handle specific types of errors that may occur in your code.

    To create a custom error, you can use the Error constructor. The Error constructor takes a string as its argument, which will be the message of the error.

    Extending the Error Class: Creating Custom Errors

    The best way to create custom errors is by creating a new class and extending it using the ‘extends’ keyword. It uses the concept of inheritance, and the custom error class inherits the properties of the Error class.

    In the constructor() function, you can initialize the properties of the custom error class.

    Syntax

    You can follow the syntax below to create custom errors by extending the Error class.

    classcustomErrorextendsError{constructor(message){super(message)// Initialize properties}}

    In the above code, we call the parent class constructor using the super() method.

    You can also initialize the properties of the customError class in the constructor function.

    Example

    In the code below, we take the input from the user. When a user clicks the check age button, it calls the checkAge() function.

    We have defined the ageError class in JavaScript code and extended it with the Error class. In the ageError class, we have added the constructor() function to initialize the properties.

    In the constructor() function, we used the super() method to initialize the message property of the Error class. Also, we have initialized the ‘name’ and ‘age’ properties in the constructor function.

    In the checkAge() function, we throw the error if the age is less than 18, and in the catch{} block, we print the error message and age.

    <html><body><p>Enter your age:<input type ="number" id ="age"/></p><button onclick ="checkAge()"> Check Age </button><p id ="demo"></p><script>const output = document.getElementById("demo");classageErrorextendsError{constructor(message, age){super(message);this.name ="ageError";this.age = age // Custom property}}functioncheckAge(){const ageValue = document.getElementById('age').value;try{if(ageValue <18){// Throw error when age is less than 18thrownewageError("You are too young", ageValue);}else{
                   output.innerHTML ="You are old enough";}}catch(e){
                output.innerHTML ="Error: "+ e.message +". <br>";
                output.innerHTML +="Age: "+ e.age +"<br>";}}</script></body></html>

    Output

    Enter your age: 5
    Check Age
    Error: You are too young.
    Age: 5
    

    If you want to create multiple new classes for the custom errors only to provide the clarified error type and message and don’t want to change the properties of the Error class, you can use the syntax below.

    classInputErrorextendsError{};

    Let’s learn it via the example below.

    Example

    In the code below, we have created 3 different custom classes and extended them with the Error class to create custom errors.

    In the try{} block, we throw the StringError.

    In the catch{} block, we used the instanceOf operator to check the type of the error object and print the error message accordingly.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");classStringErrorextendsError{};classNumberErrorextendsError{};classBooleanErrorextendsError{};try{thrownewStringError("This is a string error");}catch(e){if(e instanceofStringError){
                output.innerHTML ="String Error";}elseif(e instanceofNumberError){
                output.innerHTML ="Number Error";}elseif(e instanceofBooleanError){
                output.innerHTML ="Boolean Error";}else{
                output.innerHTML ="Unknown Error";}}</script></body></html>

    Output

    String Error
    

    Multilevel Inheritance

    You can create a general custom error by extending it with the Error class. After that, you can extend the custom error class to create a more generalized error class.

    Let’s understand it via the example below.

    Example

    In the code below, we have defined the ‘NotFound’ class and extended it using the Error class.

    After that, we defined the ‘propertyNotFound’ and ‘valueNotFound’ classes and extended them with the ‘NotFound’ class. Here, we have done the multilevel inheritance.

    In the try block, we throw a valueNotFound error if the array doesn’t contain 6.

    In the catch block, we print the error.

    <html><body><div id ="output"></div><script>const output = document.getElementById("output");classNotFoundextendsError{constructor(message){super(message);this.name ="NotFound";}}// Further InheritanceclasspropertyNotFoundextendsNotFound{constructor(message){super(message);this.name ="propertyNotFound";}}// Further InheritanceclassElementNotFoundextendsNotFound{constructor(message){super(message);this.name ="ElementNotFound";}}try{let arr =[1,2,3,4,5];// Throw an error if array doesn't contain 6if(!arr.includes(6)){thrownewpropertyNotFound("Array doesn't contain 6");}}catch(e){
             output.innerHTML = e.name +": "+ e.message;}</script></body></html>

    Output

    propertyNotFound: Array doesn't contain 6
    

    You can also throw the propertyNotFound error if any object doesn’t contain the particular property.

  • JavaScript – Custom Errors

    Custom errors are a way to create user-defined error types in JavaScript. This can be useful for handling specific types of errors, such as database errors or HTTP errors.

    JavaScript contains multiple built-in objects for the errors. Whenever any error occurs in the JavaScript code, it throws an instance of the Error class. However, you can also throw the instance of the Error class with a custom message using the ‘throw’ statement.

    In some conditions, developers need to create custom errors. For example, you are taking the user’s age in the input. If the user’s age is not above 18, you can throw a custom error like ‘ageNotValid’ for more clarification.

    Let’s understand the syntax of the Error class first, and then you will learn to create custom errors.

    The Error Class

    In JavaScript, Error is a generic class for the errors. You can create an instance of the Error class and pass the custom message as an argument.

    The Error class contains three properties: name, message, and stack.

    So, you can assume the syntax of the Error class as shown below.

    classError{constructor(message){this.message = message;this.name ="Error";this.stack =<call stack>;}}

    The ‘stack’ property is a non-standard property in the above syntax. It is supported by the Firefox browser only.

    Creating Custom Errors Using the Instance of the Error Class

    The easiest way to create a custom error is to create an instance of the Error class and change its properties.

    Syntax

    You can follow the syntax below to create custom errors by changing the properties of the instance Error class.

    const customError =newError(message);
    customError.name ="CustomError";

    Here, we have created the ‘Error’ class instance and passed the ‘message’ as an argument. Also, we have changed the value of the ‘name’ property. Similarly, you can change the value of the ‘message’ property if you don’t want to pass it as an Error() constructor argument.

    Parameter

    • message − It is a text message to represent the error.

    Example

    In the code below, we have created the instance of the Error class and stored it in the ‘customError’ variable. After that, we changed the value of the ‘name’ property to the ‘CustomError’.

    In the try{} block, we have used the ‘throw’ statement to throw the custom error, and in the catch{} block, we print the error name and message.

    <html><body><div id ="output"></div><script>const customError =newError("This is a custom error");
          customError.name ="CustomError";try{throw customError;}catch(err){
             document.getElementById("output").innerHTML = err;}</script></body></html>

    Output

    CustomError: This is a custom error
    

    Creating the Custom Errors Using the Function Constructor

    You can use the function constructor to create the template for the object. The function constructor should contain the ‘name’ and ‘message’ properties.

    Next, you can change the prototype of the function constructor with the prototype of the Error class.

    Syntax

    You can follow the syntax below to create custom errors using the constructor of the function class.

    functionvalidationError(messag, name){this.message = messag;this.name = name;}
    validationError.prototype =Error.prototype;

    In the above syntax, we have defined the validationError() function, taking the message and name as a parameter. After that, we initialize the message and name properties of the function with parametric values.

    Next, we change the prototype of the function with the prototype of the Error class.

    Example

    In the code below, we have defined the validationError() function constructor and inherited it using the prototype of the Error class.

    In the try{} block, we have defined the ‘str’ variable and initialized it with the numeric value. After that, we validate the type of the ‘str’ variable using the typeof operator. If it is not a string, we throw ‘validationError’ by passing the message and name as an argument.

    In the catch{} block, we print the message on the web page. You can run the code, and observe the error in the output.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");functionvalidationError(message ="", name ="validationError"){this.message = message;this.name = name;}
          validationError.prototype =Error.prototype;try{let str =10;if(typeof str !="string"){thrownewvalidationError("Not a string","NotStringError");}else{
                output.innerHTML ="String is valid";}}catch(e){
             output.innerHTML = e.name +": "+ e.message;}</script></body></html>

    Output

    NotStringError: Not a string
    

    Creating Custom Errors by Extending the Error Class

    The best way to create custom errors is by creating a new class and extending it using the ‘extends’ keyword. It uses the concept of inheritance, and the custom error class inherits the properties of the Error class.

    In the constructor() function, you can initialize the properties of the custom error class.

    Syntax

    You can follow the syntax below to create custom errors by extending the Error class.

    classCustomErrorextendsError{constructor(message){super(message)// Initialize properties}}

    In the above code, we call the parent class constructor using the super() method.

    You can also initialize the properties of the CustomError class in the constructor function.

    You can use any of the above approaches to create custom errors according to your requirements.

  • JavaScript – Debugging

    What is Debugging?

    Debugging in JavaScript is a process of examining JavaScript code and finding erros and fixing them. Every now and then, developers commit mistakes while coding. This error can be logical, syntax, or runtime errors. An error in a program or a script is referred to as a bug.

    The process of finding and fixing bugs is called debugging and is a normal part of the development process. This section covers tools and techniques that can help you with debugging tasks.

    Let’s look at the different methods of debugging.

    Use a JavaScript Debugger

    A debugger is an application that places all aspects of script execution under the control of the programmer. Debuggers provide fine-grained control over the state of the script through an interface that allows you to examine and set values as well as control the flow of execution.

    Once a script has been loaded into a debugger, it can be run one line at a time or instructed to halt at certain breakpoints. Once execution is halted, the programmer can examine the state of the script and its variables in order to determine if something is amiss. You can also watch variables for changes in their values.

    Nowadays, all modern browser comes with built-in debuggers. You can use the console of the browser to debug the JavaScript code.

    How to Open Console in the Browser?

    In this section, you will learn to open the console in different browsers.

    Open Console in Chrome

    Press the Below keys.

    • Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J
    • macOs − Cmd + Option + I or Cmd + Option + J

    OR

    • Step 1 − Open Chrome web browser and open the web page in a new window.
    • Step 2 − Right-click anywhere on the web page.
    • Step 3 − It will pop up menu. Select the last option, which is ‘inspect’.
    • Step 4 − It will open a Chrome developer tool.
    • Step 5 − Go to the console tab.

    Open Console in Firefox

    Press the Below keys.

    • Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J
    • macOs − Cmd + Option + I or Cmd + Option + J

    OR

    • Step 1 − Open Firefox web browser and open the web page in a new window.
    • Step 2 − Right-click anywhere on the web page.
    • Step 3 − Select the last option from the popup menu, which is ‘inspect(Q)’.
    • Step 4 − It will open a developer tool.
    • Step 5 − You can move from the ‘inspector’ tab to the ‘console’ tab.

    Open Console in Microsoft Edge

    Press the Below keys.

    • Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J
    • macOs − Cmd + Option + I or Cmd + Option + J

    OR

    • Step 1 − Open the Microsoft Edge browser.
    • Step 2 − Right-click anywhere on the web page.
    • Step 3 − Click on ‘inspect’ in the popup menu.
    • Step 4 − You will see the developer tool is opened.
    • Step 5 − Next, you can change the ‘Elements’ tab to the ‘Console’ tab in the developer tool.

    Open Console in Safari

    Press the Below keys.

    • Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J
    • macOs − Cmd + Option + I or Cmd + Option + J

    OR

    • Step 1 − Open the Safari web browser.
    • Step 2 − Open the Safari main menu from the top menu bar.
    • Step 3 − Choose ‘preferences’ in the dropdown menu. Next, choose the ‘advanced’ option.
    • Step 4 − Check the checkbox named ‘Enable Show Develop menu in menu bar’ to enable the developer tool. Next, close the preference window.
    • Step 5 − Next, reopen the main menu and select ‘Develop. After that, select the ‘Show Error Console.

    Open Console in Opera

    Press the Below keys.

    • Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J
    • macOs − Cmd + Option + I or Cmd + Option + J

    OR

    • Step 1 − Open the Opera browser.
    • Step 2 − Open the main menu from the top corner.
    • Step 3 − In the main menu, select the ‘Developer. It will open the sub-menu.
    • Step 4 − In the submenu, select the ‘developer tools.
    • Step 5 − Next, select the ‘console. It will open a console.

    Using the console.log() method

    The console.log() method prints the message in the web browser’s console. It can print primitive values, objects, variable values, etc.

    You can print the variable’s value in the console you want to debug.

    Syntax

    Users can follow the syntax below to use the console.log() method.

    Console.log(val1, val2,...);

    The console.log() method takes the comma-separated arguments to print in the web browser’s console.

    Example

    In the code below, we add the value of the num1 and num2 variables. In the browser, you can see that the sum is 32 rather than 5.

    So, you are required to debug the code.

    When you print the type of the num1 and num2 into the console, it shows that the type of the num1 is a string. So, it converts the value of the num2 variable into the string and appends it with the value of the num1.

    <html><body><div id ="output"></div><p>Note: To see the resullt in console, please open it before you run the code.</p><script>let num1 ="3";let num2 =2;let sum = num1 + num2;
          document.getElementById("output").innerHTML ="The sum is: "+ sum;
          console.log("typeof num1 is "+typeof num1);
          console.log("typeof num2 is "+typeof num2);</script></body></html>

    Output

    The sum is: 32
    Note: To see the resullt in console, please open it before you run the code.
    

    It will produce the following result in the web console −

    typeof num1 is string
    VM75616:7 typeof num2 is number
    

    Example

    In the code below, we have a person object containing various properties. We print the firstname and lastname properties of the person object in the web browser. It prints undefined.

    To find the error, you are required to debug the code. Next, we print the object in the console and found that the Person object doesn’t contain the firstname and lastname properties; instead of that, it contains the ‘name’ property.

    <html><body><div id ="demo"></div><p>Note: To see the resullt in console, please open it before you run the code.</p><script>let output = document.getElementById("demo");let person ={
             name:"John",
             age:25,
             city:"New York"}
          output.innerHTML ="The name of the person is: "+ person.name +"<br>";
          output.innerHTML +="The city of the person is: "+ person.city +"<br>";
          console.log(person);</script></body></html>

    Output

    The name of the person is: John
    The city of the person is: New York
    Note: To see the resullt in console, please open it before you run the code.
    

    It will produce the following result in the web console −

    {name: 'John', age: 25, city: 'New York'}
    

    Using the debugger Keyword

    You can go to your browser’s console’s ‘source’ panel to debug the code.

    The ‘debugger’ keyword allows you to force-stop the execution of the JavaScript code.

    Stopping the execution of the JavaScript code allows you to debug the code line-by-line.

    Once you find the bug or everything looks fine, you can resume the execution of the JavaScript code.

    You can open the console and run the below code in the browser. It will automatically pause the code, and you can observe the values of the variables to debug the code.

    Example

    The below example is the same as above. We have added the ‘debugger’ keyword before it prints the values of the object properties.

    It will pause the execution of the code before printing the values of properties. After that, when you click on the resume button, it will resume the execution of the code.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");const person ={
             name:"John",
             age:25,
             city:"New York"}debugger;
          output.innerHTML ="The name of the person is: "+ person.name +"<br>";
          output.innerHTML +="The city of the person is: "+ person.city;</script></body></html>

    Output

    The name of the person is: John
    The city of the person is: New York
    

    You will see the result in console similar to the below screenshot. To see the resullt in console, please open it before you run the code.

    Debugger Keyword

    The above image shows the pause button at the top of the browser window and the object or variables in the bottom-right corner. This way, you can check variable values and debug the code to fix the bugs.

    Setting Break Points in the Browser’s Debugger

    Setting up breakpoints is the same as using the ‘debugger’ keyword to debug the JavaScript code. So, this is an alternative way.

    In the ‘source’ panel, you can click on the line number where you want to add a breakpoint, as shown in the image below.

    After that, when you execute the JavaScript code, it will stop the execution of the code, and you can observe the variable values on the right side.

    Debugging break point

    Example

    We have defined the test() function in the example code below. The test() function concatenates the str1 and str2 strings.

    We have opened the ‘source’ panel in the browser in the developer tool. After that, we have added the breakpoint on the line ‘let res = str1.concat(str2);’. So, the debugger will stop the execution of the code at this line, and you can click the resume button to resume the execution of the code.

    <html><body><div id ="output">The resultant string after appending str2 to str1 is:</div><script>functiontest(){let str1 ="Hi";let str2 ="";let res = str1.concat(str2);
             document.getElementById("output").innerHTML += res;}test();</script></body></html>

    Output

    The resultant string after appending str2 to str1 is: Hi
    

    You will see the result in console similar to the below screenshot. To see the resullt in console, please open it before you run the code.

    Debugging break point output

    Useful Tips for Developers

    You can keep the following tips in mind to reduce the number of errors in your scripts and simplify the debugging process −

    • Use plenty of comments. Comments enable you to explain why you wrote the script the way you did and to explain particularly difficult sections of code.
    • Always use indentation to make your code easy to read. Indenting statements also makes it easier for you to match up beginning and ending tags, curly braces, and other HTML and script elements. You can use the code formatters in the IDE.
    • Write modular code. Whenever possible, group your statements into functions. Functions let you group related statements and test and reuse portions of code with minimal effort.
    • Be consistent in the way you name your variables and functions. Try using names that are long enough to be meaningful and that describe the variable’s contents or the function’s purpose.
    • Use consistent syntax when naming variables and functions. In other words, keep them all lowercase or all uppercase; if you prefer Camel-Back notation, use it consistently.
    • Test long scripts in a modular fashion. In other words, do not try to write the entire script before testing any portion of it. Write a piece and get it to work before adding the next portion of code.
    • Use descriptive variable and function names and avoid using single-character names.
    • Watch your quotation marks. Remember that quotation marks are used in pairs around strings and that both quotation marks must be of the same style (either single or double).
    • Watch your equal signs. You should not use a single = for comparison purposes.
    • Declare variables explicitly using the var keyword.
  • JavaScript – try…catch

    JavaScript try…catch Statement

    The try-catch statement in JavaScript is used to handle the runtime errors (exceptions). This is very common in most programming languages to handle exceptions. A try-catch statement can handle only runtime errors. The try block must be followed by either exactly one catch block or one finally block (or one of both).

    Inside the try{} statement, you can write the code having errors or possibilities of the errors. You can add regular JavaScript code into the try{} statement.

    The catch{} statement is used to handle the errors. When any error occurs in the code of the try{} statement, the JavaScript run engine executes the code of the catch{} statement to handle the errors.

    If no error occurs in the code of the try{} statement, it will skip the code of the catch{} statement and execute the next lines of the code.

    Syntax

    You can follow the syntax below to use the try-catch statements in the code to handle exceptions.

    try{// JavaScript code}catch(error){// Handle error}

    You can print the error object in the catch{} statement or the custom error message based on the error type to show errors.

    Parameters

    • error − The catch{} statement takes the error object as a parameter. It contains the name and message property. However, it is an optional parameter.

    Example

    In the code below, we assign the num1 variables value to the num variable inside the try{} statement. Here, the num1 variable is not defined. So, it will throw an error.

    In the catch{} statement, we print the value of the error object’s name and message property.

    In the output, you can observe that it throws a reference error with a proper error message.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");try{let num = num1;}catch(err){
             output.innerHTML +="The error name is: "+ err.name +"<br>";
             output.innerHTML +="The error message is: "+ err.message +".<br>";}</script></body></html>

    Output

    The error name is: ReferenceError
    The error message is: num1 is not defined.
    

    When any error occurs in the try{} statement, it skips the execution of the remaining code and executes the code of the catch{} statement.

    Lets understand it via the example below.

    Example

    In the code below, we invoke the welcome() function, which is not defined. So, it will throw a reference error.

    In the catch{} statement, we handle the error.

    In the output, you can see that it prints the start message of the try{} statement, the start message of the catch{} statement, and the error message. It skips the end message of the try{} statement as an error occurs before that.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");try{
             output.innerHTML +="In the start of try block <br>";welcome();
             output.innerHTML +="In the end of try block <br>";}catch(err){
             output.innerHTML +="In the catch block <br>";
             output.innerHTML +="The error name is: "+ err.name +"<br>";
             output.innerHTML +="The error message is: "+ err.message +".<br>";}</script></body></html>

    Output

    In the start of try block
    In the catch block
    The error name is: ReferenceError
    The error message is: welcomeis not defined.
    

    Note − The try-catch statement doesnt allow you to handle the syntax errors. It can handle only runtime errors.

    For example, if you run the below code. It will show you an error in the browsers console but cant catch the error using the {} statement.

    try{let num =;}catch(err){// Error handling}

    JavaScript trycatchfinally Statement

    The finally{} statement allows you to execute the particular code after completing the execution of the try{} and catch{} statements.

    JavaScript always executes the code of the finally{} statement, whether the error occurs in the code of the try{} statement. If an error occurs, it executes the code of the catch{} statement and then executes the code of the finally{} statement.

    Example

    In the code below, we assign the value of the variable ‘b’ to the variable ‘a’ inside the try{} statement. It throws an error.

    In the catch{} statement, we print the error.

    In the finally{} statement, it prints the message.

    You can observe the output that it runs the code of the try{} statement first, the code of the catch{} statement after that, and the code of the finally{} statement at last.

    <html><body><div id ="output"></div><script>try{let a = b;}catch(e){
             document.getElementById("output").innerHTML = e;}finally{
             document.getElementById("output").innerHTML +="<br>Finally block always executes";}</script></body></html>

    Output

    ReferenceError: b is not defined
    Finally block always executes
    

    Example

    In the example below, we have written the code without any error into the try{} statement.

    Also, we have added the catch{} and finally{} statements.

    The output shows that it executes the try{} statement code and finally{} statement code after that. It skips the execution of the catch{} statement, as the code is error-free.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");try{let a =10;
             output.innerHTML ="Value of a is "+ a +"<br>";}catch(e){
             output.innerHTML = e.name +" : "+ e.message;}finally{
             output.innerHTML +="Inside the finally block.";}</script></body></html>

    Output

    Value of a is 10
    Inside the finally block.
    

    JavaScript Throw Statement

    When any error occurs in the code, JavaScript throws an error by default. But you can also throw the error manually. For example, you are doing the form data validation. If the data is invalid, you can throw the error and ask users to correct the data.

    When you throw an error using the throw statement, the code present after that in the try{} statement will not executed, and it will execute the code of the catch{} statement.

    You can follow the syntax below to throw an error using the throw statement.

    throw<error>;

    In the above syntax, <error> can be a Error object, string, number, primitive value, or a particular type of error object. It is a good practice to throw an Error object rather than throwing the primitive value.

    Example: Throwing the Error object

    In the code below, we throw an Error object from the try{} statement using the throw statement. It stops the execution of the remaining code of the throw statement and executes the code of the catch{} statement.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");try{
             output.innerHTML +="Start of the try block. <br />";thrownewError("Custom error");
             output.innerHTML +="End of the try block. <br />";//not executed}catch(e){
             output.innerHTML +="Catch block: Caught exception. <br />";
             output.innerHTML += e.name +" : "+ e.message;}</script></body></html>

    Output

    Start of the try block
    Catch block: Caught exception.
    Error: Custom error
    

    Example: Throwing the primitive value

    In the code below, we throw the primitive numeric value from the try{} statement. In the catch{} statement, we get the thrown primitive value and print it.

    <html><body><div id ="output">The error message is:</div><script>try{throw20;}catch(e){
             document.getElementById("output").innerHTML += e;}</script></body></html>

    Output

    The error message is: 20
    

    Example: Input Validation Example

    In the code below, we have defined the <input> element of the number type to take the user age as an input.

    When the user clicks the submit age button, it invokes the handleAge() function. The handleAge() function checks whether the age is less than 18. If yes, it throws the rangeError.

    The catch{} statement prints the error message to validate the age.

    <html><body><p>Age:<input type ="number" id ="age" value ="20"></p><button onclick ="handleAge()"> Submit Age </button><p id ="demo"></p><script>const output = document.getElementById("demo");functionhandleAge(){let age = document.getElementById("age").value;try{if(age <18){throwRangeError("You are not eligible to vote");}else{
                   output.innerHTML +="<br>You are eligible to vote";}}catch(e){
                output.innerHTML +="<br>The error is - "+ e;}}</script></body></html>

    Output

    Age: 20
    Submit Age
    The error is - RangeError: You are not eligible to vote
    

    Nesting Try Blocks

    Sometimes, developers are required to write the nested try-catch statements. The nested try-catch means a try block inside the try block.

    If the inner catch{} statement cant handle the error, the outer catch{} statement may handle it. You can also skip the inner catch{} statement, but in this case, you need to write the finally{} statement with the try{} statement.

    Example

    We have used the two nested try{} statements in the code below. We have added the try-finally statement inside the outer try{} statement.

    The inner try{} statement throws the error, handled in the outer catch{} statement.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");try{try{throwError("Error in the inner try block");}finally{
                output.innerHTML +="Inside the inner finally block. <br>";}}catch(e){
             output.innerHTML +="Inside the outer catch block. <br>";
             output.innerHTML +="Error: "+ e.message;}</script></body></html>

    Output

    Inside the inner finally block.
    Inside the outer catch block.
    Error: Error in the inner try block
    

    The Rethrow Error

    Sometimes, it can happen that the catch{} statement cant handle the error. In such cases, you can rethrow the error from the catch block using the throw statement.

    The outer catch{} statement can handle the rethrown error if it is available.

    Example

    In the code below, we have created the two nested try-catch blocks. In the inner try block, we throw the error using the throw statement. The inner catch{} statement will catch the error, and we rethrow the error from the inner catch{} statement.

    After that, we handle the error in the outer catch{} statement.

    <html><body><div id ="demo"></div><script>let output = document.getElementById("demo");try{try{throw20;}catch(e){// Rethrowing the error.
                output.innerHTML ="Inside the inner catch block. <br>";
                output.innerHTML +="Error: "+ e +"<br> <br>";throw e;}}catch(e){
             output.innerHTML +="Inside the outer catch block. <br>";
             output.innerHTML +="Error: "+ e;}</script></body></html>

    Output

    inside the inner catch block.
    Error: 20
    
    Inside the outer catch block.
    Error: 20
    

    Conditional Catch-blocks

    Inside the catch{} block, you can use the if-else statement to handle the errors conditionally. In this way, you can use the single catch{} statement for the multiple try{} statements.

    In the catch{} statement, you can check the type of the error using the instanceOf operator and handle the error according to the error type.

    Example

    In the code below, we have called the welcome function inside the try{} statement, and the welcome() function is not defined.

    In the catch{} statement, we check the type of the error using the instanceOf operator and print the message on the web page according to the type of the error.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");try{welcome();// Function not defined}catch(e){if(e instanceofReferenceError){
                output.innerHTML ="Reference error is occurred.";}elseif(e instanceofTypeError){
                output.innerHTML ="Type error is occurred.";}elseif(e instanceofRangeError){
                output.innerHTML ="Range error is occurred.";}elseif(e instanceofSyntaxError){
                output.innerHTML ="Syntax error is occurred.";}else{
                output.innerHTML ="Error is occurred.";}}</script></body></html>

    Output

    Reference error is occurred.
    

    JavaScript try…catch with setTimeout() Method

    Using the try-catch statement with the asynchronous JavaScript code wont catch the error thrown from the try block.

    The reason is that JavaScript executes the asynchronous code, when all main thread code gets executed.

    Lets understand it via the example below.

    Example

    In the code below, we used the setTimeOut() method inside the try{} statement. It executes the callback function after 1000 milliseconds. In the callback function, we throw the error using the throw statement.

    In the output, you can observe that the cathc{} statement is not catching the error, and it prints the error in the browsers console.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");try{
             output.innerHTML ="Inside the try block. <br>";setTimeout(()=>{thrownewError("Whoops!");},1000);}catch(err){
             output.innerHTML +="Inside the catch block. <br>";
             output.innerHTML = err;}</script></body></html>

    Output

    Inside the try block.
    

    Promise-based Errors

    When any error occurs while consuming the promise code, you can use the catch() method to handle the error. Alternatively, you can pass the error handler as a second parameter of the then() method.

    Examples

    In the code below, we have created the promise and rejected it after 1000 milliseconds.

    After that, we used the then() and catch() method to handle the promise. Here, we have rejected the promise so that control will execute the code of the catch() method.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");
          output.innerHTML ="The promise is pending...";let promise =newPromise((resolve, reject)=>{setTimeout(()=>{reject("The promise is rejected!");},1000);});
          promise
          .then((result)=>{
             output.innerHTML = result;}).catch((error)=>{
             output.innerHTML = error;});</script></body></html>

    Output

    The promise is rejected !
    

    Types of Errors in JavaScript

    There are different types of errors that JavaScript can throw. Here, we will learn each type one by one with examples.

    JavaScript Range Error

    The JavaScript code throws a range error when the value is out of the specified range.

    Example

    In the code below, we used the toPrecision() method and passed 1000 as an argument. It throws the range error, as the number cant have 1000 digits.

    <html><body><div id ="output"></div><script>try{let num =10;
             num.toPrecision(1000);}catch(err){
             document.getElementById("output").innerHTML = err;}</script></body></html>

    Output

    RangeError: toPrecision() argument must be between 1 and 100
    

    JavaScript Reference Error

    The reference error occurs when you try to access the undefined variables, functions, class methods, etc.

    Example

    In the code below, we execute the test() method of the window object. Here, the test() method is not defined, so it throws the reference error.

    <html><body><div id ="output"></div><script>try{
             window.test();}catch(err){
             document.getElementById("output").innerHTML = err;}</script></body></html>

    Output

    TypeError: window.test is not a function
    

    JavaScript Type Error

    The JavaScript code throws the type error if you dont use the values of the valid type with methods or operators.

    Example

    In the example below, we use the toLowerCase() method with the boolean variable, but the toLowerCase() method is supported by string values only. So, it throws the type error.

    <html><body><div id ="output"></div><script>try{let bool =true;
             bool.toLowerCase();}catch(err){
             document.getElementById("output").innerHTML = err;}</script></body></html>

    Output

    TypeError: bool.toLowerCase is not a function
    

    JavaScript URI (Uniform Resource Identifier) Error

    The URI error occurs when you dont pass the valid URL as an argument of the encodeURI, decodeURI, etc. methods.

    Example

    In the example below, we passed the invalid encoded URI as an argument of the decodeURI() method. So, it throws the URIError.

    <html><body><div id ="output"></div><script>try{decodeURI("%");}catch(err){
             document.getElementById("output").innerHTML = err;}</script></body></html>

    Output

    URIError: URI malformed
  • JavaScript – Errors & Exceptions Handling

    Error handling in JavaScript is a process to detect and handle errors that occurs during the execution of a program. Errors can be a syntax, runtime or logical errors. An error occurred during the execution of the program is called a runtime error or an exception.

    In JavaScript, errors can occur due to programming mistakes, incorrect user input, etc. Errors can disrupt code execution and lead to bad user experience. Effective error & exception handling is required for building robust, reliable and user friendly applications in JavaScript.

    What is an Error?

    An error is an event that occurs during the execution of a program that prevents it from continuing normally. Errors can be caused by a variety of factors, such as syntax errors, runtime errors, and logical errors.

    Syntax Errors

    Syntax errors, also called parsing errors, occur at compile time in traditional programming languages and at interpret time in JavaScript.

    For example, the following line causes a syntax error because it is missing a closing parenthesis.

    <script>
       window.print();</script>

    When a syntax error occurs in JavaScript, only the code contained within the same thread as the syntax error is affected, and the rest of the code in other threads gets executed, assuming nothing in them depends on the code containing the error.

    Runtime Errors (Exceptions)

    Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).

    For example, the following line causes a runtime error because the syntax is correct here, but at runtime, it is trying to call a method that does not exist.

    <script>
       window.printme();</script>

    Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal execution.

    There are many JavaScript runtime errors (exceptions), some are as follows −

    • ReferenceError − Trying to access an undefined variable/ method.
    • TypeError − Attempting an operation on incompatible data types.
    • RangeError − A value exceeds the allowed range.

    Logical Errors

    Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and do not get the expected result.

    For example, when you divide any numeric value with 10, it returns undefined.

    <script>let num =10/0;</script>

    What is Error Handling?

    Whenever any error occurs in the JavaScript code, the JavaScript engine stops the execution of the whole code. If you handle such errors in the proper way, you can skip the code with errors and continue to execute the other JavaScript code.

    You can use the following mechanisms to handle the error.

    • try…catch…finally statements
    • throw statements
    • the onerror() event handler property
    • Custom Errors

    The try…catch…finally Statement

    The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try…catch…finally construct as well as the throw operator to handle exceptions.

    You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.

    Here is the try…catch…finally block syntax −

    <script>try{// Code to run[break;]}catch( e ){// Code to run if an exception occurs[break;]}[finally{// Code that is always executed regardless of // an exception occurring}]</script>

    The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the try block, the exception is placed in e and the catch block is executed. The optional finally block executes unconditionally after try/catch.

    Example

    Here is an example where we are trying to call a non-existing function which in turn is raising an exception.

    Let us try to catch this exception using try…catch and display a user-friendly message. You can also suppress this message, if you want to hide this error from a user.

    You can use finally block which will always execute unconditionally after the try/catch.

    <html><head><script>try{var a =100;alert(myFunc(a));}catch(e){alert(e);}finally{alert("Finally block will always execute!");}</script></head><body><p>Exception handling using try...catch...finally statements</p></body></html>

    Output

    Exception handling using try...catch...finaly statements
    

    The throw Statement

    You can use throw statement to raise your built-in exceptions or your customized exceptions. Later these exceptions can be captured and you can take an appropriate action.

    Example

    The following example demonstrates how to use a throw statement.

    <html><head><script>functionmyFunc(){var a =100;var b =0;try{if( b ==0){throw("Divide by zero error.");}else{var c = a / b;}}catch( e ){alert("Error: "+ e );}}</script></head><body><p>Click the following to see the result:</p><form><input type ="button" value ="Click Me" onclick ="myFunc();"/></form></body></html>

    Output

    Click the following to see the result:
    Click Me
    

    You can raise an exception in one function using a string, integer, Boolean, or an object and then you can capture that exception either in the same function as we did above, or in another function using a try…catch block.

    The onerror Event Handler Property

    The onerror event handler was the first feature to facilitate error handling in JavaScript. The onerror is an event handler property of the ‘window’ object, which automatically triggers when any error occurs on any element of the web page. You can call the callback function when any error occurs to handle the error.

    You can follow the syntax below to use the onerror event handler property.

    window.onerror = errorhandler_func;OR<ele onerror="errorhandler_func()"></ele>

    In the above syntax, errorhandler_func() will be executed when any error will occur.

    The onerror event handler provides three pieces of information to identify the exact nature of the error −

    • Error message − The same message that the browser would display for the given error
    • URL − The file in which the error occurred
    • Line number − The line number in the given URL that caused the error

    Example

    In the code below, we added the onclick event on the <input> element, and we called the myFunc() function when users click the input element. The myFunc() function is not defined. So, it will throw an error.

    We used the ‘onerror’ event handler to catch the error. In the callback function, we print the error message, file URL, and line number in the file where the error occurs.

    <html><body><p> Click the following button to see the result:</p><form><input type ="button" value ="Click Me" onclick ="myFunc();"/></form><div id ="demo"></div><script>const output = document.getElementById("demo");
          window.onerror=function(msg, url, line){
             output.innerHTML ="Error: "+ msg +"<br>";
             output.innerHTML +="URL: "+ url +"<br>";
             output.innerHTML +="Line: "+ line +"<br>";}</script></body></html>

    Output

    Click the following button to see the result:
    Click Me
    Error: Uncaught ReferenceError: myFunc is not defined
    URL: file:///C:/Users/Lenovo/Desktop/intex.html
    Line: 5
    

    You can use an onerror method, as shown below, to display an error message in case there is any problem in loading an image.

    <img src="myimage.gif" onerror="alert('An error occurred loading the image.')"/>

    You can use onerror with many HTML tags to display appropriate messages in case of errors.

    The JavaScript Error Class and Error Object

    Whenever any error occurs in the code, JavaScript throws an instance (object) of the error class. The error object contains the information about the error.

    However, Error() is a generic constructor for all types of errors, but different objects exist for different types of errors.

    JavaScript Custom Errors

    You can also throw an error with the custom message using the Error() constructor.

    const customError =newError(message);
    customError.name ="CustomError";

    Here, we have created the ‘Error’ class instance and passed the ‘message’ as an argument. Also, we have changed the value of the ‘name’ property. Similarly, you can change the value of the ‘message’ property if you don’t want to pass it as an Error() constructor argument.

    JavaScript Error Object Reference

    JavaScript Error Types or Constructor

    JavaScript contains the below types of errors. You can also use it as a constructor to create a new error of the specific type.

    Error Type/ObjectDescription
    ErrorIt is a generic constructor for the error. You can also create custom errors by extending the Error object.
    SyntaxErrorThe instance of the SyntaxError is thrown when any error is in the syntax. For example, missing parenthesis, invalid JSON, etc.
    ReferenceErrorThe reference error occurs when you try to access variables not defined in the current scope.
    TypeErrorWhen the types of the variables is not valid, JavaScript throws the type error.
    RangeErrorWhen numeric input is out of range, it throws the range error.
    URIErrorJavaScript throws the URIError when you pass invalid arguments to the decodeURI or encodeURI methods.
    EvalErrorDeprecated.
    AggregateErrorIt is used to aggregate multiple error objects into a single error object, and it allows you to handle multiple error objects.

    Error Object Properties

    The Error object contains the two properties.

    PropertyDescription
    nameIt is used to set or get an error name.
    messageIt is used to set or get an error message.

    Non-Standard Properties and Methods

    Here is the list of the non-standard properties and methods of the Error object. However, they are not supported by all browsers. So, you should avoid using them.

    PropertyDescription
    columnNumberIt is supported in the Firefox browser only.
    descriptionIt is supported in the Microsoft browser only.
    displayNameIt is supported in the Firefox browser only.
    fileNameIt is supported in the Firefox browser only.
    lineNumberIt is supported in the Firefox browser only.
    numberIt is supported in the Microsoft browser only.
    stackIt is supported in the Firefox browser only.
    internalError()It is supported in the Firefox browser only.
    toSource()It is a Non Standard method of the Error object.