JavaScript – Tagged Templates

JavaScript – Tagged Templates ”; Previous Next JavaScript Tagged Templates The tagged templates in JavaScript are an advanced version of the template literals. You can define the function to format the string and use it with a template literal to format the string according to the functionality of the function. The tagged template can be used with the string using the function name only, and it does not need to add the parenthesis while using the function. Syntax Following is the syntax to use the tagged templates in JavaScript − function format(str, exp1, exp2, …expN) { // Format the string } let res = format`${exp1} abcd ${exp2}`; The format() function works as a template tag in the above syntax. The function takes multiple parameters, which you can use inside the function body to format the string. Parameters str − It is an array of strings of template literal. exp1, exp2, …expN − They are expressions of the template literals. Examples Example: Basic Tagged Template In the example below, we have defined the format() function. The format() function takes the array of strings as a parameter. The function body joins all elements of the str array, converts the string into the upper case using the toUpperCase() method, and returns the updated string. In the output, you can see that the template tagged has converted the string into uppercase. <html> <body> <p id = “output”> </p> <script> function format(str) { return str.join(“”).toUpperCase(); } let res = format`Hi How are you?`; document.getElementById(“output”).innerHTML = res; </script> </body> </html> Output HI HOW ARE YOU? Example: Expression with Tagged Templates In the example below, the format() function takes the array of strings and name variable as a parameter. We join all string instances in the function body and append the name at the end. After that, return the updated string. In the output, you can see the name at the end of the string. <html> <body> <p id = “output”> </p> <script> function format(str, name) { return str.join(” “) + name; } let name = “John”; let res = format`Hi ${name}, How are you?`; document.getElementById(“output”).innerHTML = res; </script> </body> </html> Output Hi , How are you?John Example: Using Rest Parameter You can also use the spread operator (parameter) to collect all expressions in the single function parameters. Otherwise, you need to pass the parameter for each expression used in the string separately. In the below example, we use spread operator to pass two parameters, name and price. In output you can notice the values of the parameters (arguments) are displayed. <html> <body> <div id = “output1”> </div> <div id = “output2”> </div> <script> function format(str, …values) { document.getElementById(“output1″).innerHTML = values; return str.join(” “) + values[1]; } const price = 100; let name = “John” const res = format`Hi,${name} The price is ${price}`; document.getElementById(“output2″).innerHTML = res; </script> </body> </html> Output John,100 Hi, The price is 100 Print Page Previous Next Advertisements ”;

JavaScript – History Object

JavaScript – History Object ”; Previous Next Window History Object In JavaScript, the window ”history” object contains information about the browser”s session history. It contains the array of visited URLs in the current session. The ”history” object is a property of the ”window” object. The history property can be accessed with or without referencing its owner object, i.e., window object. Using the ”history” object”s method, you can go to the browser”s session”s previous, following, or particular URL. History Object Methods The window history object provides useful methods that allow us to navigate back and forth in the history list. Follow the syntax below to use the ”history” object in JavaScript. window.history.methodName(); OR history.methodName(); You may use the ”window” object to access the ”history” object. JavaScript History back() Method The JavaScript back() method of the history object loads the previous URL in the history list. Syntax Follow the syntax below to use the history back() method. history.back(); Example In the below code”s output, you can click the ”go back” button to go to the previous URL. It works as a back button of the browser. <html> <body> <p> Click “Go Back” button to load previous URL </p> <button onclick=”goback()”> Go Back </button> <p id = “output”> </p> <script> function goback() { history.back(); document.getElementById(“output”).innerHTML += “You will have gone to previous URL if it exists”; } </script> </body> </html> JavaScript History forward() Method The forward() method of the history object takes you to the next URL. Syntax Follow the syntax below to use the forward() method. history.forward(); Example In the below code, click the button to go to the next URL. It works as the forward button of the browser. <html> <body> <p> Click “Go Forward” button to load next URL</p> <button onclick = “goforward()”> Go Forward </button> <p id = “output”> </p> <script> function goforward() { history.forward(); document.getElementById(“output”).innerHTML = “You will have forwarded to next URL if it exists.” } </script> </body> </html> JavaScript History go() Method The go() method of the history object takes you to the specific URL of the browser”s session. Syntax Follow the syntax below to use the go() method. history.go(count); In the above syntax, ”count” is a numeric value representing which page you want to visit. Example In the below code, we use the go() method to move to the 2nd previous page from the current web page. <html> <body> <p> Click the below button to load 2nd previous URL</p> <button onclick = “moveTo()”> Move at 2nd previous URL </button> <p id = “output”> </p> <script> function moveTo() { history.go(-2); document.getElementById(“output”).innerHTML = “You will have forwarded to 2nd previous URL if it exists.”; } </script> </body> </html> Example In the below code, we use the go() method to move to the 2nd previous page from the current web page. <html> <body> <p> Click the below button to load 2nd next URL</p> <button onclick = “moveTo()”> Move at 2nd next URL </button> <p id = “output”> </p> <script> function moveTo() { history.go(2); document.getElementById(“output”).innerHTML = “You will have forwarded to 2nd next URL if it exists.”; } </script> </body> </html> Following is the complete window history object reference including both properties and methods − History Object Property List The history object contains only the ”length” property. Property Description length It returns the object”s length, representing the number of URLS present in the object. History Object Methods List The history object contains the below 3 methods. Method Description back() It takes you to the previous web page. forward() It takes you to the next web page. go() It can take you to a specific web page. Print Page Previous Next Advertisements ”;

JavaScript – Self-Invoking Functions

JavaScript – Self-Invoking Functions ”; Previous Next Self-Invoking Functions The self-invoking functions are JavaScript functions that execute immediately as they are defined. To define a self-invoking function, you can enclose an anonymous function within parentheses followed by another set of parentheses. These are also called self-executing anonymous functions. The anonymous function inside the first pair of parentheses is basically a function defined with function expression. So a self-invoking function is also called immediately invoked function expression (IIFE). Syntax The syntax to define the self-invoking functions in JavaScript is as follows − (function () { // function body })(); The function definition is enclosed inside the pair of parentheses. The second pair of parentheses at the end executes the function. An alternative syntax is as follows − (function () { // function body }()); The first syntax is more clear. Example In the example below, we print the message in the output using the self-executing function. <html> <body> <p id = “output”> </p> <script> (function () { document.getElementById(“output”).innerHTML = “Self-invoked function is executed!”; }()); </script> </body> </html> Output Self-invoked function is executed! Self-Invoking Functions with Parameters You can create a self-invoking function with parameters and pass arguments to it. It is common practice to pass references to global objects such as window, etc. (function (paras) { // function body })(args); The paras are the list of parameters in the definition of the anonymous function and the args are arguments passed. Example In the below example, we created an anonymous function with a parameter name. We have passed an argument to it. <html> <body> <div id = “demo”></div> <script> const output = document.getElementById(“demo”); (function (name) { output.innerHTML = `Welcome to ${name}`; })(“Tutorials Point !”); </script> </body> </html> Output Welcome to Tutorials Point ! Private Scope of Self-Invoking Functions Whatever code is defined inside the self-executing function remains in the private scope and doesn”t pollute the global scope. So, developers can make code clear and remove the errors like naming conflicts, etc. Also, the code of the self-invoking function remains hidden and can”t be accessible by other parts of the code. Example In the example below, we have defined the variable ”a” outside or inside the function. The variable defined outside is a global variable, and the variable defined inside the function is a private variable, limited to the self-executing function”s scope. Also, we have printed the value of the variable from inside and outside of the function. Users can observe the variable”s value in the output. In this way, we can avoid the naming conflicts. <html> <body> <div id = “output”> </div> <script> const output = document.getElementById(“output”); let a = 10; (function () { output.innerHTML += “Entering to the function <br/>”; var a = 20; output.innerHTML += “The value of a is ” + a + “<br>”; output.innerHTML += “Exiting to the function <br/>”; }()); output.innerHTML += “The value of the outside the function is ” + a; </script> </body> </html> Output Entering to the function The value of a is 20 Exiting to the function The value of the outside the function is 10 Example In some cases, it is required to access the variable of the self-executing function outside of the function. In this case, we can make that variable global using the ”window” object as shown below and access the variable in the global scope. <html> <body> <div id = “output”> </div> <script> (function () { var string = “JavaScript”; window.string = string; })(); document.getElementById(“output”).innerHTML = “The value of the string variable is: ” + string; </script> </body> </html> Output The value of the string variable is: JavaScript Private scope of a self-invoking function can be accessed by using the call() or apply() methods. Benefits of Using the Self-Invoking Functions Avoiding the global scope − Developers can avoid the global scope for variables and functions using the self-invoking function, helping to avoid naming conflict and making code more readable. Initialization − The self-executing functions can be used for the initialization of variables. Code privacy − Programmers can avoid accessing the code of the self-executing function by other parts of the code. Print Page Previous Next Advertisements ”;

JavaScript – Function Invocation

JavaScript – Function Invocation ”; Previous Next Function Invocation The function invocation in JavaScript is the process of executing a function. A JavaScript function can be invoked using the function name followed by a pair of parentheses. When you write a function code in JavaScript, it defines the function with expressions and statements. Now, to evaluate these expressions, it is necessary to invoke the function. The function invocation is the synonym of the function call or function execution. A JavaScript function can be defined using function declaration or function expression. The code inside the curly braces in the function definition are not executed when function is defined. To execute the code, we need to invoke the function. The call a function and invoke a function are two interchangeable terms are commonly used. But we can invoke a function without calling it. For example, self-invoking functions are invoked without calling them. Syntax The syntax of function invocation in JavaScript is as follows – functionName() OR functionName(arg1, arg2, … argN); Here ”functionName” is the function to be invoked. We can pass as many arguments as the number of parameters listed in function definition. Example In the example below, we have defined the merge() function taking two parameters. After that, we used the function name to invoke the function by passing the arguments. <html> <body> <p id = “output”> </p> <script> function merge(str1, str2) { return str1 + str2; } document.getElementById(“output”).innerHTML = merge(“Hello”, ” World!”); </script> </body> </html> Output Hello World! Invocation of Function Constructor When you invoke a function with the ”new” keyword, it works as a function constructor. The function constructor is used to create an object from the function definition. Syntax Following is the syntax to invoke the function as a constructor. const varName = new funcName(arguments); In the above syntax, we invoked the function with a ”new” keyword and passed the arguments. Example In the example below, we use the function as an object template. Here, the ”this” keyword represents the function object, and we use it to initialize the variables. After that, we invoke the function car with the ”new” keyword to create an object using the function template. <html> <body> <p id = “output”> The ODCar object is: </p> <script> function Car(name, model, year) { this.name = name; this.model = model; this.year = year; } const ODCar = new Car(“OD”, “Q6”, 2020); document.getElementById(“output”).innerHTML += JSON.stringify(ODCar); </script> </body> </html> Output The ODCar object is: {“name”:”OD”,”model”:”Q6″,”year”:2020} Object Method Invocation We haven”t covered JavaScript objects yet in this tutorial but we will cover it in upcoming chapters. Here, let”s learn the object method invocation in short. The JavaScript object can also contain the function, and it is called the method. Syntax Following is the syntax below to invoke the JavaScript object method. obj.func(); In the above syntax, the ”obj” is an object containing the method, and ”func” is a method name to execute. Example In the example below, we have defined the ”obj” object containing the ”name” property and the ”getAge()” method. Outside the object, we access the method by the object reference and invoke the method. In the output, the method prints 10. <html> <body> <p id = “output”>The age of John is: </p> <script> const obj = { name: “John”, getAge: () => { return 10; } } document.getElementById(“output”).innerHTML += obj.getAge(); </script> </body> </html> Output The age of John is: 10 Self-Invoking Functions The self-invoking functions in JavaScript are executed just after they are defined. There is no need to call these types of function to invoke them. The self-invoking functions are always defined using anonymous function expression. These types of functions are also called immediately invoked function expressions (IIFEs). To invoke these function, we wrap the function expression within a grouping operator (parentheses) and then add a pair of parentheses. Example Try the following example. In this example, we define a function to show a “Hello world” message in alert box. <html> <head> <script> (function () {alert(“Hello World”)})(); </script> </head> <body> </body> </html> Other methods to invoke the function JavaScript contains two special methods to invoke the function differently. Here, we have explained each method in the table below. Method Function invocation Arguments Call() Immediate invocation Separate arguments Apply() Immediate invocation Array of arguments The difference between the call() and apply() method is how it takes the function arguments. We will learn each of the above methods with examples in the next chapters one by one. Print Page Previous Next Advertisements ”;

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 ”;