JavaScript – Classes

JavaScript – Classes ”; Previous Next JavaScript Classes The JavaScript classes are a blueprint or template for object creation. They encapsulate the data and functions to manipulate that data. We can create the object using classes. Creating an object from a class is referred to as instantiating the class. In JavaScript, the classes are built on prototypes. The classes are introduced to JavaScript in ECMAScript 6 (ES6) in 2009. For example, you can think about writing code to represent the car entity. A code can contain the class having car properties. For different cars, you can create an instance of the class and initialize the car properties according to the car model. Before ES6, the constructor function was used to define a blueprint of the object. You can define the constructor function as shown below. function Car(brand) { // Constructor function this.brand = brand; // property initialization } const carObj = new Car(“Audi”); // Creating an object Defining JavaScript Classes The syntax of the class is very similar to the constructor function, but it uses the ”class” keyword to define the class. As we can define a function using function declaration or function expression, the classes are also can be defined using class declaration or class expression. Syntax The syntax of class definition in JavaScript is as follows − // class declaration class ClassName { // Class body } //Class expression const ClassName = class { // class body } A ”ClassName” is a class name in the above syntax. A JavaScript class is a function, but you can”t use it as a regular function. Type of JavaScript Classes A JavaScript class is a type of function. In the example below, we used the ”typeof” operator to get the type of the class. It returns the ”function’, which you can observe in the output. <!DOCTYPE html> <html> <body> <p id = “output”> The type of the car class is: </p> <script> class Car { // Class body } document.getElementById(“output”).innerHTML += typeof Car; </script> </body> </html> Output The type of the car class is: function The constructor() method When you use the function as an object blueprint, you can initialize the object properties inside the function body. Similarly, you need to use the constructor() method with the class to initialize the object properties. Whenever you create an instance of the class, it automatically invokes the constructor() method of the class. In below example, we use the constructor() method to create a Car class − class Car { constructor(brand) {// Defining the constructor this.brand = brand; } } The constructor() method has no specific name but can be created using the ”constructor” keyword. You can initialize the class properties using the ”this” keyword inside the constructor function. Creating JavaScript Objects To create an object of a JavaScript class, we use new operator followed by the class name and a pair of parentheses. We can pass thee arguments to it also. Let”s create an object called myCar as follows − const myCar = new Car(“Audi”); The this keyword inside the constructor function refers to an object that is executing the current function. Example: Creating class objects without arguments In the example below, we have defined the ”Car” class. The class contains the constructor and initializes the properties with default values. After that, we have created the instance of the class, and you can observe it in the output. <!DOCTYPE html> <html> <body> <p id = “output”> </p> <script> // creating Car class class Car { constructor() { this.brand = “BMW”; this.model = “X5”; this.year = 2019; } } // instantiate myCar object const myCar = new Car(); // display the properties document.getElementById(“output”).innerHTML = “Car brand is : ” + myCar.brand + “<br>” +”Car model is : ” + myCar.model + “<br>” +”Car year is : ” + myCar.year + “<br>”; </script> </body> </html> Output Car brand is : BMW Car model is : X5 Car year is : 2019 If you want to initialize the class properties dynamically, you can use the parameters with the constructor() method. Example: Creating class objects with arguments In the example below, we have defined the ”Car” class. The constructor() method of the class takes 4 parameters and initializes the class properties with parametric values. While creating the ”Car” class instance, we passed 4 arguments. In this way, you can initialize the class properties dynamically. <!DOCTYPE html> <html> <body> <p id = “output”> </p> <script> class Car { constructor(brand, model, price, year) { this.brand = brand; this.model = model; this.price = price; this.year = year; } } const carObj = new Car(“BMW”, “X5”, 9800000, 2019); document.getElementById(“output”).innerHTML += “Car brand : ” + carObj.brand + “<br>” + “Car model : ” + carObj.model + “<br>” + “Car price : ” + carObj.price + “<br>” + “Car year : ” + carObj.year + “<br>” </script> </body> </html> Output Car brand : BMW Car model : X5 Car price : 9800000 Car year : 2019 JavaScript Class Methods You can also define the methods inside the class, which can be accessed using the class instance. Syntax Follow the syntax below to define methods inside the class. class car { methodName(params) { // Method body } } obj.methodName(); In the above syntax, ”methodName” is a dynamic name of the method. To define a class method, you don”t need to write any keyword like ”function” before the method name. To invoke the class method, you need to use the instance of the class. Here, ”obj” is an instance of the class. You can also pass the parameters to the method. Example The example below demonstrates how to pass parameters to the class methods. Here, we have defined the updateprice() method to update the price of the car. So, while invoking the updateprice() method, we pass the new price as an argument and use it inside the method body to update the price. You can see the original and updated price of the car in the output. <!DOCTYPE html> <html>

JavaScript – Default Parameters

JavaScript – Default Parameters ”; Previous Next The default parameters in JavaScript are a feature that allows you to specify a default value for a function parameter. The concept of the default parameters was introduced in the ES6. We can initialize the parameters with the default values. So, if the function is called with missing argument or argument with an undefined value, it uses the default value of the parameter in the function. The default value of a function parameter is “undefined” in JavaScript. When a function is called with missing arguments the parameters are set to ”undefined”. The undefined parameter values are acceptable but can generate unusual outcomes. Before the ES6 version of JavaScript, we needed to check whether the parameter value was “undefined” inside the function body. If yes, they need to initialize the parameter with the proper value. Let”s understand it via the example below. function sum(p, q) { return p + q; } sum(10, 20); // 30 sum(10); // NaN sum(); // NaN In this example, we observe the following − sum(10, 20) returns the sum of the two arguments, i.e., 30. Here both arguments are passed. sum(10) returns NaN. Here only one argument is passed. The second parameter q is set to undefined. Mathematical operation on undefined returns NaN. sum() also returns NaN. Here both arguments are missing. So they are set to undefined. When we call the function with missing argument values, it returns NaN which is unusual. To overcome this problem, we can use default parameter values to be used if function is called with missing argument values. Default Parameters Syntax The syntax to use the function default parameters in JavaScript is as follows – function functName(param1 = defaultValue1, param2 = DefaultValue2, ..) { // Use parameters here } In the above syntax, the default value of the param1 is set to defaultValue1, and the default value of the param2 is set to defaultValue2. Let”s look at the example below − Example (Default parameters) In the below code, parameter p and q contains the 30 and 40 default values, respectively. In the output, unlike the first example, you can see that it returns the sum of the default parameter values when any argument is missing. <html> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); function sum(p = 30, q = 40) { return p + q; } output.innerHTML += “sum(10, 20) -> ” + sum(10, 20) + “<br>”; // 10 + 20 = 30 output.innerHTML += “sum(10) -> ” + sum(10) + “<br>”; // 10 + 40 = 50 output.innerHTML += “sum() -> ” + sum() + “<br>”; // 30 + 40 = 70 </script> </body> </html> Output sum(10, 20) -> 30 sum(10) -> 50 sum() -> 70 Passing an expression as a default parameter value We can pass an expression as a default parameter value to a JavaScript function. The expression can also contain the values of the previous parameters. Example We pass the expression as a default parameter value in the code below. The expression contains the value of the previous parameters. In the output of the second function call, you can observe that the value of the r is 100, which is equal to (p = 5) * (q = 10) * 2. We haven”t passed any argument in the third function call, so all parameters take the default value. <html> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); function sum(p = 2, q = p * 2, r = p * q * 2) { return p + q + r; } output.innerHTML += “sum(5, 10, 15) -> ” + sum(5, 10, 15) + “<br>”; // 5 + 10 + 15 = 30 output.innerHTML += “sum(5, 10) -> ” + sum(5, 10) + “<br>”; // 5 + 10 + (5 * 10 * 2) = 115 output.innerHTML += “sum() -> ” + sum() + “<br>”; // 2 + 4 + 16 = 22 </script> </body> </html> Output sum(5, 10, 15) -> 30 sum(5, 10) -> 115 sum() -> 22 You can”t use the uninitialized parameter in the expression. Otherwise, the code will raise a reference error. Passing Undefined Argument When you pass the undefined argument to the function call, the JavaScript function definition uses the default parameter values to avoid unnecessary errors. <html> <body> <p id=”output”> </p> <script> let output = document.getElementById(“output”); function sum(p = 24, q = 26) { return p + q; } output.innerHTML += “sum(5, undefined) -> ” +sum(5, undefined)+”<br>”; // 5 + 26 = 31 output.innerHTML += “sum(undefined) -> ” + sum(undefined) + “<br>”; // 24 + 26 = 50 </script> </body> </html> Output sum(5, undefined) -> 31 sum(undefined) -> 50 Function expression as a default parameter The JavaScript function expression can also be paased as a fucntion default parameter. In the example below, the getNum() function returns 5. We used the function expression as a default value of parameter q. The output shows that when the second argument is missing, the parameter uses the value returned from the getNum() function. <html> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); function getNum() { return 5; } function mul(p = 5, q = getNum()) { return p * q; } output.innerHTML += “mul(10) -> ” + mul(10) + “<br/>”; output.innerHTML += “mul() -> ” + mul() + “<br/>”; </script> </body> </html> Output mul(10) -> 50 mul() -> 25 Function Optional Parameters The function default parameters are also called the optional parameters, as the function will give output without any error even if we don”t pass the arguments for the optional parameter. You should pass all required parameters at the start and optional parameters at the function end. function sum(p, q=10){ return p+q; } In the above JavaScript code snippet, we put the optional parameter q at the end of the parameter list. Example The JavaScript code below shows that the first parameter is required, and the second parameter is optional. <html> <body> <p

JavaScript – Comma Operator

JavaScript – Comma Operator ”; Previous Next JavaScript Comma Operator The comma operator (,) in JavaScript evaluates the multiple expression from left to right. You can use the resultant value of the left expression as an input of the right expression. After evaluating all expressions, it returns the resultant value of the rightmost expression. However, the comma operator is also used in the ”for” loop, array, object, etc. In this chapter, you will learn all the use cases of the comma operator. Syntax You should follow the below syntax to use the comma expression to evaluate multiple expressions. var answer = (exp1, exp2, exp3, ex4, …); Return value It returns the resultant value of the last expression only. Examples Let”s understand the JavaScript comma operator in details with the help of some exmaples Example: The Comma Operator with Strings In the example below, we have added the 4 comma seprated strings in the braces. Here, each string works as an expression. The code will evaluate the string and return the last string. In the output, you can see that it prints the ”CSS” as it is the rightmost string. <html> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); let ans = (“JavaScript”, “Python”, “HTML”, “CSS”); output.innerHTML = “The value of the ans variable is: ” + ans; </script> </body> </html> Example: The Comma Operator with Expressions In the example below, we have defined the variable ”a” and initialized it with 5. In the ”ans” variable, we store the resultant value the comma operator returns. The first expression updates the value of a to 8, the second expression increments the value of a by 1, and the third expression adds 2 to the updated value of the variable ”a”. The value of the ”ans” is 11, which is returned by the rightmost expression of the comma operator. <html> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); let a = 5; let ans = (a = 8, a++, a += 2); output.innerHTML = “The value of the ans variable is: ” + ans; </script> </body> </html> Example: The comma operator with functions In the example below, we have defined the first() and second() functions. Also, it prints the message and returns the value from the function according to the function name. We use the comma operator to execute the multiple functions. In the output, you can see that it invokes both functions but prints the returned value from the second() function only. <html> <body> <p id=”output”> </p> <script> let output = document.getElementById(“output”); function first() { output.innerHTML += “The first function is called! <br/>”; return 1; } function second() { output.innerHTML += “The second function is called! <br/>”; return 2; } let ans = (first(), second()); output.innerHTML += “The value of the ans variable is: ” + ans; </script> </body> </html> Other Use Cases of The Comma Operator For defining the multiple variables in a single row. let m = 1, n = 2, x = 3; To initialize the array with multiple elements. const arr = [10, 20, 30, 40, 50, 60]; For defining the object with multiple properties. const obj = { name: “tutorialspoint”, age: 10, … other properties } You can use the comma operator for loop to initialize or update multiple variables in each iteration. for(let p = 0, q = 1; p < n; p++, q++) { // Code for the loop } To pass multiple parameters of arguments into the functions. function func(param1, param2, … ) { // function code } OR func(10, 20, 30, …); To import or export import { func2, variable } from ”./module2.js”; OR export {func1, variable, num}; To destructure arrays of objects. let [a, b, c] = [34, 72, 23]; To print multiple variables in the console. console.log(a, b, c) // a, b, and c are variables. Print Page Previous Next Advertisements ”;

ECMAScript 2022

JavaScript – ECMAScript 2022 ”; Previous Next The ECMAScript 2022 standard was released in 2022. Important features added to this update include private methods and fields, Array at() and String at() methods etc. This chapter discuss all the newly added features in ECMAScript 2022. New Features Added in ECMAScript 2022 Here are the new methods, features, etc., added to the ECMAScript 2022 version of JavaScript. Array at() Method String at() Method Private methods and fields Object.hasOwn() error.cause await import Here, we have explained each feature in detail. Array at() Method ECMAScript 2022 (ES2022) introduced Array at() method to arrays. In JavaScript, array at() method used to access the array element from the particular index. You can”t use the negative index in the arr[index] representation, but with the array.at() method, you can also use the negative index to access array elements. When you use the negative index, it returns the array from the last. Example In the below code, we access the last and third-last elements from the array using the negative indexes and array.at() method. <body> <div id = “demo1”>The last array element is: </div> <div id = “demo2”>The third last array element is: </div> <script> const arr = [10, 20, 60, 72, 6, 12, 23]; document.getElementById(“demo1”).innerHTML += arr.at(-1); document.getElementById(“demo2”).innerHTML += arr.at(-3); </script> </body> </html> Output The last array element is: 23 The third last array element is: 6 String at() Method ECMAScript introduced String at() method to strings. In JavaScript, the String at() method is used to access the characters from the particular string index. It also accepts the negative index as an argument. Example In the code below, we access the last and fourth last characters from the string using the negative indexes and string.at() method. <html> <body> <div id = “demo1”>The last string character is: </div> <div id = “demo2”>The fourth last string character is: </div> <script> let str = “Hello world”; document.getElementById(“demo1”).innerHTML += str.at(-1); document.getElementById(“demo2″).innerHTML += str.at(-4); </script> </body> </html> Output The last string character is: d The fourth last string character is: o Private Methods and Fields ECMAScript 2022 introduced the way to write private methods and fields. In JavaScritp, you can write the field name or method name followed by the hash sign (”#”) to make them private. You can”t access the private fields and methods using the class instance. However, you can access them inside the class. Example In the below code, the car class contains the ”brand” private field and the ”carBrand” private method. The getBrand() method is public. We have created the instance of the car class and invoked the getBrand() method using it. The getBrand() method calls the carBrand() method. <html> <body> <div id = “output”> </div> <script> class car { #brand; constructor(brand) { this.#brand = brand; } getBrand() { return this.#carBrand(); } #carBrand() { return “The car brand is ” + this.#brand; } } const BMW = new car(“BMW”); document.getElementById(“output”).innerHTML = BMW.getBrand(); </script> </body> </html> Output The car brand is BMW Object hasOwn() Method The Object.hasOwn() method is a replacement for the Object.hasOwnProperty() method. It is used to check whether the object contains a particular property. Example In the code below, we use the hasOwn() method to check whether the obj object contains the name property. <html> <body> <div id = “output”> </div> <script> const obj = { name: “sam”, age: 50, } document.getElementById(“output”).innerHTML = “Does obj contain name property? ” + obj.hasOwnProperty(“name”); </script> </body> </html> Output Does obj contain name property? true The error.cause Property The ”cause” is a property of the JavaScript object. It represents the reason for the error. It is introduced in ECMAScript 2022. Example In the below code, we throw a new error from the ”try” block. Also, we specify the reason for the error using the cause property. We access the ”cause” property value in the catch block to know the reason. <html> <body> <div id = “demo”> </div> <script> let output = document.getElementById(“demo”); try { output.innerHTML += “Inside the try block <br>”; throw new Error(“New error”, { cause: “Testing with error.” }) } catch (error) { output.innerHTML += “The reason for the error is: ” + error.cause + “<br>”; } </script> </body> </html> Output Inside the try block The reason for the error is: Testing with error. The Await Import You can use the asynchronous import to import the dynamic modules. You need to use the ”await” keyword for the asynchronous import. For example, the below code contains the self-invoking asynchronous function. Also, the ”await” keyword is used inside the function to await the import. (async function () { await (await import(”./math.js”)).default(); await (await import(”./operations.js”)).default(); })(); Warning – Some of the above features are not supported by some browsers. So, you can use the polyfill to avoid errors. Print Page Previous Next Advertisements ”;

JavaScript – WeakSet

JavaScript – The WeakSet Object ”; Previous Next The JavaScript WeakSet object is a collection of objects. The WeakSet is very similar to the Set. The main difference between the WeakSet and Set is that the WeakSet contains only objects, and the Set can also contain the values like numbers, Boolean, string, etc. WeakSet objects are weak, meaning that references to objects in a WeakSet are held weakly. If no other references to a value stored in the WeakSet exist, those values can be garbage collected. WeakSet objects are useful for keeping track of objects without preventing them from being garbage collected. An example of this would be keeping track of DOM nodes without having to remove them from the DOM manually. Syntax Follow the syntax below to define a new instance of the WeakSet class in JavaScript. const weakest = new WeakSet([iterable]); We used the WeakSet() constructor function with a ”new” keyword in the above syntax. Parameters iterable − It is an iterable containing multiple objects to initialize the WeakSet. In JavaScript, if two objects contain the same properties and value, they are still different as their references are different. Here, we have listed the methods and properties of the WeakSet. WeakSet Properties Here is a list of all the properties of WeakSet and their description. Sr.No. Property & Description 1 constructor It returns the WeakSet constructor function. WeakSet Methods Here is a list of the methods associated with WeakSet object and their description. Sr.No. Methods & Description 1 add() To insert the object into the WeakSet. 2 delete() To delete a single object from the WeakSet. 3 has() Check whether a particular object exists in the WeakSet. Examples Example: Similar Objects with WeakSet In the example below, we have defined the obj1 and obj2 empty objects and added them to the WeakSet. Also, we used the has() method to check whether the set contains the obj1 and obj2 objects. Both objects look similar but have different references in the memory. So, the WeakSet contains both objects. <html> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); const obj1 = {}; const obj2 = {}; const weak_set = new WeakSet([obj1, obj2]); if(weak_set.has(obj1)) { output.innerHTML += “The weak_set contains the obj1 object! <br>”; } if(weak_set.has(obj2)) { output.innerHTML += “The weak_set contains the obj2 object! <br>”; } </script> </body> </html> Output The weak_set contains the obj1 object! The weak_set contains the obj2 object! Example: Add Object in WeakSet In the example below, we have defined the WeakSet containing 0 elements. Also, we have defined the car object and used the add() method to add the object in the set. After that, we use the has() method to check whether the object has been added into the WeakSet. <html> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); const weak_set = new WeakSet(); const car = { brand: “Audi”, model: “Q5”, } weak_set.add(car); if (weak_set.has(car)) { output.innerHTML = “The car object is added successfully to the weak_set.”; } </script> </body> </html> Output The car object is added successfully to the weak_set. Example: Delete Object from the WeakSet In the example below, we have initialized the WeakSet with the car object. After that, we use the delete() method to delete the object from the WeakSet. <html> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); const car = { brand: “Audi”, model: “Q5”, } const carWeakSet = new WeakSet([car]); const flag = carWeakSet.delete(car); // returns true if deleted successfully output.innerHTML = “The car object is deleted successfully from the carWeakSet? ” + flag; </script> </body> </html> Output The car object is deleted successfully from the carWeakSet? true WeakSet is not iterable. So, you can”t traverse through its elements. Print Page Previous Next Advertisements ”;

JavaScript – Function bind()

JavaScript – Function bind() Method ”; Previous Next Function bind() Method The function bind() method in JavaScript creates a new function with a specified this value and optional arguments, without invoking the original function immediately. It is commonly used to set the context (this) for a function and partially apply arguments. This method is used to bind a particular object to a common function. To understand the function bind() method, we should first understand the “this” keyword. In JavaScript (and other programming languages also), this is a special keyword that is used within functions to refer to the object on which the function is invoked. The value of this is depended on how a function is being called and behaviour of this can vary in different contexts. Syntax The syntax of JavaScript function bind() method is as follows − functionToBind.bind(thisValue, arg1, arg2, …); Here functionToBind is the original function whose this value and arguments you want to set. Parameters thisValue − The value that should be passed as the this parameter when the new function is called. arg1, arg2, … − Optional arguments that will be fixed (partially applied) when the new function is called. These arguments will be prepended to the arguments provided to the new function. Lets now understand the Function bind() method with the help of some program examples. Without Function bind() Method Here we will create a general and common function greet() which simply prints to the console. We create a constant object named person and give it some property i.e. name and we then invoke the function greet by passing it a message “Hello”. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(“demo”); function greet(message) { output.innerHTML = message + ”, ” + this.name; } const person = { name: ”John Doe” }; greet(”Hello”); </script> </body> </html> Output Hello, In this example, when the greet function is called directly without using bind, the this value is not explicitly set, leading to an undefined or global object (window in a browser environment) being used as this. With Function bind() method To overcome the issue in the previous code where it could not fetch any associated name, we make use of the bind function to bind the object person to the function greet. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(“demo”); // Original function function greet(message) { output.innerHTML = message + ”, ” + this.name; } // Object with a ”name” property const person = { name: ”John Doe” }; const greetPerson = greet.bind(person, ”Hello”); greetPerson(); </script> </body> </html> Output Hello, John Doe The bind method was able to create a new function greetPerson wherein the this value has been explicitly set to the person object and argument “Hello” is partially applied as in the previous code as well. Using bind() ensures that the function is executed in the desired context, preventing issues related to the default behaviour of this in JavaScript functions. Example: Binding different objects to same function We have created three objects with x and y coordinates of a point, a function printVal is created to print to the console the coordinates of the point. The bind method binds the points to the printVal function and prints the x, y coordinates of each of the points. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(“demo”); const points1 = { X: 100, Y: 100 } const points2 = { X: 200, Y: 100 } const points3 = { X: 350, Y: 400 } function printVal() { output.innerHTML += “Coordinates: “+this.X + “,” + this.Y + “<br>”; } const printFunc2 = printVal.bind(points1); printFunc2(); const printFunc3 = printVal.bind(points2); printFunc3(); const printFunc4 = printVal.bind(points3); printFunc4(); </script> </body> </html> Output Coordinates: 100,100 Coordinates: 200,100 Coordinates: 350,400 Example: Setting the default values of function parameters This is a new scenario wherein we make use of the bind function to predefine the parameter. The multiply() function simply takes 2 inputs and returns their product. By using the bind() method we can set any of the parameters to a default value as needed. In the below example, it sets the variable y to 2 and hence upon calling the function by passing just 1 parameter i.e. x as 5 it gets multiplies by the preset 2 and returns the output of 5×2=10. <html> <body> <div id = “output”> </div> <script> // Original function with parameters function multiply(x, y) { return x * y; } // Using bind to preset the first parameter const multiplyByTwo = multiply.bind(null, 2); // Calling the bound function with only the second parameter document.getElementById(“output”).innerHTML= multiplyByTwo(5); </script> </body> </html> Output 10 It is important to note that the bind method creates and returns a new function and does not modify the original function. The same function can be reused and yet made to match different use cases without actually modifying. Print Page Previous Next Advertisements ”;

JavaScript – WeakMap

JavaScript – The WeakMap Object ”; Previous Next A WeakMap object in JavaScript is a collection of key-value pairs where the keys are weakly referenced. The WeakMap keys must be objects or non-registered symbols, and values are of any arbitrary JavaScript type. The WeakMap is similar to the JavaScript Map. The main difference between the WeakMap and Map data structure is that the WeakMap data structure uses the objects as a key only, but Map can use other data types also as a key. If you use the value of another data type as a key of a WeakMap except the object, it gives the Types error. Syntax You can follow the syntax below to use the WeakMap in JavaScript − const weak_map = new WeakMap(); In the above syntax, we used the ”new” keyword with a WeakMap() function to create a new instance of the WeakMap. The WeakMap provides methods to set, get, and delete the key-value pairs from the WeakMap. Here, we have listed the properties and methods of the WeakMap. WeakMap Properties Here is a list of the properties of WeakMap and their description − Sr.No. Name & Description 1 constructor To get a constructor function of a WeakMap. WeakMap Methods Here is a list of the methods associated with WeakMap object and their description − Sr.No. Name & Description 1 delete() To delete a single key-value pair from the WeakMap. 2 get() To get values related to the specific object. 3 has() Check whether a particular object exists as a key exists in the WeakMap. 4 set() To insert the key-value pair in the WeakMap. WeakMap Constructor() Following is the WeakMap constructor in JavaScript − Sr.No. Name & Description 1 WeakMap() To create a WeakMap object. Examples Example: Inserting key-value pair to the WeakMap In the example below, we have defined the WeakMap using the constructor function. After that, we used the set() method to set the laptop object as a key and its price as a value. At last, we used the get() method to get the value related to the ”laptop” key. <html> <body> <p id = “output”>The laptop price is: </p> <script> const wm = new WeakMap(); const laptop = { brand: “HP”, model: “Pavilion”, } wm.set(laptop, 100000); document.getElementById(“output”).innerHTML += wm.get(laptop); </script> </body> </html> Output The laptop price is: 100000 If we execute the program, it returns the value related to the “laptop” key, i.e. “10000”. Example: Deleting key-value pair from the WeakMap In the example below, we have inserted the key-value pair in the WeakMap using the set() method. After that, we used the delete() method to delete the key-value pair from the WeakMap. After deleting the key-value pair when you access it, the WeakMap returns undefined, as you can see in the output. Note − WeakMaps are not iterable in JavaScript. <html> <body> <div id = “output1”>The laptop price is: </div> <div id = “output2”>The laptop price after deletion is: </div> <script> const wm = new WeakMap(); const laptop = { brand: “HP”, model: “Pavilion”, } wm.set(laptop, 100000); document.getElementById(“output1”).innerHTML += wm.get(laptop); wm.delete(laptop); document.getElementById(“output2″).innerHTML += wm.get(laptop); </script> </body> </html> Output The laptop price is: 100000 The laptop price after deletion is: undefined It returns “undefined” as the key-value is deleted from the WeakMap. WeakMaps are not iterable in JavaScript Print Page Previous Next Advertisements ”;

JavaScript – Conditional Operators

JavaScript – Conditional Operators ”; Previous Next JavaScript Conditional Operators The conditional operator in JavaScript first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation. The conditional operator is also known as the ternary operator. The JavaScript conditional (ternary) operator is only operator that takes three operands – a condition followed by a question mark (?), then the first expression to be executed if the condition is truthy followed by a colon (:), and finally the second expression to be executed if the condition is falsy. There are six falsy values in JavaScript. These are − 0 (zero), false, empty string (”” or “”), null, undefined, and NaN. All other values are treated as truthy in JavaScript. Syntax Following is the syntax of conditional (ternary) operator in JavaScript − var variable = condition ? exp1 : exp2; Parameters Here, we have explained the parameters in the above statement. condition − It is a conditional statement. exp1 − If the conditional statement evaluates truthy, control flow executes the exp1 expression. exp2 − If the conditional statement evaluates falsy, control flow executes the exp2 expression. If the value of the condition is any falsy value, the result of the expression will be the value of exp2; otherwise, it will be the value of exp1. Example In the example below, we compare the value of the num1 and num2 variables in the conditional statement. Here, the conditional statement evaluates true, so the result variable contains the value of the first expression. <html> <body> <div id=”output”></div> <script> var num1 = 90; var num2 = 67; var res = num1 > num2 ? “num1 is greater than num2” : “num2 is greater than num1”; document.getElementById(“output”).innerHTML = res; </script> </body> </html> It will produce the following result − num1 is greater than num2 Example In the example below, we assign the value to the object property according to the conditional statement’s result. Now, imagine what if you need to write the if-else statement to assign value to each property conditionally. The code will become complex, but with the ternary operator, you can easily do it with a single line of code. <html> <body> <div id=”output”></div> <script> const year = 2004; const obj = { name: “John”, age: year < 2005 ? “adult” : “minor”, city: “New York” }; document.getElementById(“output”).innerHTML = obj.name + ” is ” + obj.age + ” and lives in ” + obj.city; </script> </body> </html> It will produce the following result − John is adult and lives in New York Example This example demonstrates that you can also use the expression instead of values. According to the conditional statement, control flow evaluates the first or second expression and assigns the resultant value to the ”result” variable. <html> <body> <div id=”output”></div> <script> let operator = ”-”; let res = operator == ”+” ? 10 + 20 : 10 – 20; document.getElementById(“output”).innerHTML = “The result is: ” + res; </script> </body> </html> It will produce the following result − The result is: -10 In short, you can use the ternary or conditional operator to shorten the code, which uses the if-else statement. Handling null values We can use the JavaScript conational operator to handle null value to set a default value if the user passes a null value. Example Try the following example − <html> <body> <div id=”output”></div> <script> const greet = (user) => { const name = user? user.name : “stranger”; return `Hello, ${name}`; }; document.getElementById(“output”).innerHTML = greet({ name: “John” }) + “<br>” + greet(null); </script> </body> </html> It will produce the following result − Hello, John Hello, stranger Print Page Previous Next Advertisements ”;

JavaScript – Closures

JavaScript – Closures ”; Previous Next What is Closure? The concept of closures in JavaScript allows nested functions to access variables defined in the scope of the parent function, even if the execution of the parent function is finished. In short, you can make global variables local or private using the closures. A JavaScript closure is basically a combination of the function and its lexical environment. This allows an inner function to access the outer function scope. A closure is created every time a function is created at the function creation time. Before you start learning the concept of closures, you need to know the concept of lexical scoping, nested functions, and returning functions. Lexical Scoping In JavaScript, the lexical scoping is a concept in which the scope of the variables is determined at the code compilation time based on the structure of the code. For example, the nested function can access the variables from the parent function”s scope is called lexical scoping. Nested Function You can define the function inside the function, and the inner function is called the nested function. Let”s learn it via the example below. Example In the example below, we have defined the inner() function inside the outer() function. Also, the inner() function is executed inside the outer() function. When we execute the outer() function, it also executes the inner() function, a nested function. <html> <body> <p id = “demo”> </p> <script> const output = document.getElementById(“demo”); function outer() { output.innerHTML += “The outer function is executed! <br>”; function inner() { output.innerHTML += “The inner function is executed! <br>”; } inner(); } outer(); </script> </body> </html> Output The outer function is executed! The inner function is executed! Returning Function When any function returns the function instead of a value or variable, it is called the returning function. Let”s look at the example below. Example In the below code, the outer() function returns the function definition, and we store it in the ”func” variable. After that, we use the ”func” variable to invoke a function stored in that. <html> <head> <title> JavaScript – Returning function </title> </head> <body> <p id = “demo”> </p> <script> const output = document.getElementById(“demo”); function outer() { output.innerHTML += “The outer function is executed! <br>”; return function inner() { output.innerHTML += “The inner function is executed! <br>”; } } const func = outer(); func(); func(); </script> </body> </html> Output The outer function is executed! The inner function is executed! The inner function is executed! Now, you learned the prerequisite required to learn the closures. The definition of JavaScript closure is a bit confusing, but we will learn the closure concept step by step so it will be clear to you. A Counter Dilemma For example, you create the counter to increment and decrement the variable. As shown below, you need to use the global variable for the counter. Example In the example below, the ”cnt”, a global variable is initialized with 100. Whenever the decrement() function is executed, it decreases the value of the ”cnt” variable by 1. <html> <body> <p id = “demo”> </p> <script> const output = document.getElementById(“demo”); var cnt = 100; function decrement() { cnt = cnt – 1; output.innerHTML += “The value of the cnt is: ” + cnt + “<br>”; } decrement(); decrement(); decrement(); </script> </body> </html> Output The value of the cnt is: 99 The value of the cnt is: 98 The value of the cnt is: 97 The above code perfectly works as a decrement counter, but the problem is ”cnt” variable can be accessed in the code anywhere, and any part of the code can change it without executing the decrement() function. Here, JavaScript closure comes into the picture. Example: JavaScript Closures The counter() function returns the decrement() function in the example below. The ”cnt” variable is defined inside the counter() function rather than in the global scope. The decrement() function decreases the value of the ”cnt” by 1 and prints in the output. The ”func” variable contains the decrement() function expression. Whenever you execute the func(), it calls the decrement() function. <html> <body> <p id = “demo”> </p> <script> const output = document.getElementById(“demo”); function counter() { let cnt = 100; // Works as a global variable for the decrement function. return function decrement() { cnt = cnt – 1; output.innerHTML += “The value of the cnt is: ” + cnt + “<br>”; } } const func = counter(); // Returns the decrement() function expression func(); func(); func(); </script> </body> </html> Output The value of the cnt is: 99 The value of the cnt is: 98 The value of the cnt is: 97 Now, let”s remember the definition of closure again. It says that the nested function can access the variables from the outer function”s scope even if the execution of the outer function is finished. Here, the execution of the counter() function is finished. Still, you can call the decrement() function and access the ”cnt” variable with an updated value. Let”s look at another example of closure. Example In the example below, the name() function returns the getFullName() function. The getFullName() function merges the string with the ”name” variable, defined in the outer function”s scope. <html> <head> <title> JavaScript – Closure </title> </head> <body> <p id = “demo”> </p> <script> const output = document.getElementById(“demo”); function name() { let name = “John”; return function getFullName() { return name + ” Doe”; } } const fullName = name(); output.innerHTML += “The full name is ” + fullName(); </script> </body> </html> Output The full name is John Doe Benefits of Closure Followings are some benefits of the closures in JavaScript − Encapsulation − The closure allows developers to hide or encapsulate the data. It makes data private and inaccessible from the global scope. So, you can expose only the required variables and functions and hide other internal details of the code. Preserving State − The function remembers its lexical scope even if the execution of the outer function is completed. So, developers can

JavaScript – Maps

JavaScript – The Maps Object ”; Previous Next A Map object in JavaScript is a collection of key-value pairs where the keys can be of any type, including objects or functions. The order of the map elements is the same as the insertion order of the key-value pairs. To create a new Map object, you can use the new Map() constructor. You can then add key-value pairs to the map using the set() method. To get the value for a particular key, you can use the get() method. To remove a key-value pair from the map, you can use the delete() method. Syntax Following is the syntax to use the Map data structure in JavaScript − const map = new Map([iterable]); In the above syntax, we used the ”new” keyword with a Map() constructor to define an instance of the Map. Parameters iterable − It is an iterable containing the key-value pairs to initialize the map with elements of the iterable. Also, it is an optional parameter. The Map class in JavaScript contains a set of built-in methods that allow us to work with Map objects. Here, we have listed the properties and methods of the Map. Map Properties Following are the properties of Map object − Sr.No. Name & Description 1 size This property returns the number of elements in this map. Map Methods In the following table, we have listed all the methods of Map object and their description − Sr.No. Name & Description 1 clear() This method removes all elements from a Map object. 2 delete() This method removes a specified element from a Map object by key. 3 entries() This method returns a new map iterator object that contains the [key, value] pairs. 4 forEach() This method executes a callback function once per each key/value pair in a Map object. 5 get() This method is used to return a specified element from a Map object. 6 has() This method indicates whether an element with the specified key exists or not. 7 keys() This method returns a new Iterator object that contains the keys for each element in the Map object. 8 set() This method insert the key-value pair to a Map object. 9 values() This method returns a new Iterator object that containing values of the Map object. JavaScript Map Constructor() Following is the constructor of Map in JavaScript − Sr.No. Name & Description 1 Map() To create a Map object. Examples Example: Creating new Map Object In the example below, we have passed the 2D array containing the key-value pairs as an argument of the Map() constructor. After that, we traverse the map to get each value of the map and show in the output. <html> <body> <div> Map elements are: </div> <div id = “output”> </div> <script> const map = new Map([[“Apple”, 100], [“Banana”, 20], [“Orange”, 50]]); for (let [key, value] of map) { document.getElementById(“output”).innerHTML += `${key} : ${value} <br>`; } </script> </body> </html> Output After executing the above program, it returns each value of the map. Map elements are: Apple : 100 Banana : 20 Orange : 50 Example: Inserting key-value pair in the Map In the example below, we use the set() method to insert the key-value pair in the map. The set() method takes the key as the first argument and the value as the second argument. <html> <body> <div>After inserting 2 key-value pairs in the map: </div> <div id = “output”> </div> <script> const map = new Map(); map.set(“Grapes”, 40); map.set(“Apples”, 50); for (let [key, value] of map) { document.getElementById(“output”).innerHTML += `${key} : ${value} <br>`; } </script> </body> </html> Output After inserting 2 key-value pairs in the map: Grapes : 40 Apples : 50 As we can see in the output, the provided [key-value] pairs have been inserted in the Map object. Example: Accessing Map Elements The get() method can be used to access the map elements. Here, we have added elements to the set. After that, we used the get() method to access the values of the name and RollId keys. <html> <body> <div id = “output1”>Name: </div> <div id = “output2”>Roll Id: </div> <script> const map = new Map(); map.set(“name”, “John”); map.set(“rollId”, 123); document.getElementById(“output1”).innerHTML += map.get(“name”); document.getElementById(“output2”).innerHTML += map.get(“rollId”); </script> </body> </html> Output After executing, it returns all the elements present in the Map object. Name: John Roll Id: 123 Example: Removing a Map Element In the example below, we use the delete() method to delete the key-value pair having a key 20. However, you can also use the clear() method to remove all elements from the map. <html> <body> <div>Map after deleting the [20,30] key-value pair: </div> <div id = “demo”> </div> <script> const output = document.getElementById(“demo”); const map = new Map([[10, 20], [20, 30], [30, 40]]); map.delete(20); // Deleting a [20,30] key-value pair from the map for (let [key, value] of map) output.innerHTML += “Key: ” + key + ” Value: ” + value + “<br/>”; </script> </body> </html> Output Map after deleting the [20,30] key-value pair: Key: 10 Value: 20 Key: 30 Value: 40 Example: Size of the Map In the below code, we used the ”size” property of the Map class to