JavaScript – Versions

JavaScript – Versions ”; Previous Next JavaScript was developed by Brendan Eich in 1995. It was standardized in 1997 by European Computer Manufacturers Association (ECMA) and officially known as ECMAScript. The first version of the language is known as ECMSScript 1 (abbreviated as ES1). The fist three versiosn (ES1, ES2, and ES3) laid the foundation of the language. The fourth version, ES4, was abandoned. The first main revision done in ES5(2009). The second major revised version is ES6 (ECMAScript 2015). After 2015, the versions are named by the year in which it it released. The latest version of JavaScript is ECMAScript 2023. JavaScript Versions In the Below table, we have specified detailed information about each version. Version Official Name Release Year Features Added ES1 ECMAScript 1 1997 First release ES2 ECMAScript 2 1998 Minor changes ES3 ECMAScript 3 1999 Added regular expressions Added do-while Added switch Added try/catch ES4 ECMAScript 4 Never Released. ES5 ECMAScript 5 2009 JavaScript strict mode Multiline strings String.trim() Array methods Object methods Getters and setters Trailing commas ES6 ECMAScript 2015 2015 let and const statements Map and set objects Arrow functions For/of loop Some array methods Symbol Classes Promises JavaScript Modules New Number methods and properties For/of loop Spread operator ES7 ECMAScript 2016 2016 Exponential (**) operator Array.includes() method ES8 ECMAScript 2017 2017 Added Async/await Added Object.entries() method Added Object.values() method Added Object.getOwnPropertyDescriptor() method Added string padding ES9 ECMAScript 2018 2018 Rest object properties JavaScript shared memory Promise.finally() method New features of the RegExp() object ES10 ECMAScript 2019 2019 String trim.start() String trim.end() Array.flat() Revised Array.sort() Revised JSON.stringify() / toString() Object.fromEntries() method ES11 ECMAScript 2020 2020 Nullish Coalescing Operator (??) BigInt primitive data type ES12 ECMAScript 2021 2021 String.replaceAll() method Promise.Any() method ES13 ECMAScript 2022 2022 The static block inside the class New class features Top-level await ES14 ECMAScript 2023 2023 Array findLast() & findLastIndex() Hashbang Grammer Symbols as WeakMap keys Since 2016, early update is being released with version named by the year of release. The update release in June 2023 is known as ECMAScript 2023. Browser Support All modern browsers fully support the ES1 to ES6. For other versions, you may use Polyfill and write the additional code. Chrome Firefox Microsoft Edge Opera Safari Firefox Android Yes Yes Yes Yes Yes Yes Print Page Previous Next Advertisements ”;

JavaScript – Native Prototypes

JavaScript – Native Prototypes ”; Previous Next Native Prototypes The native prototypes in JavaScript are property of Object.prototype object. The prototypes are the mechanism by which the objects inherit features from one another. In JavaScript, each object contains the prototype property. The prototype of each object contains the methods and properties related to the object. So, it is also called the native prototype. However, you can update or add new methods and properties to the native prototype object, but you can”t delete any already existing. The JavaScript object and object constructor are the main prerequisites to understand JavaScript native prototypes. Syntax You can follow the syntax below to access the native prototype of the object. Object.prototype; In the above syntax, the object can be any JavaScript object. Example: Accessing the array”s prototype Whenever you execute the below code in the browser, it will print the prototype of the array in the browser console. In the same way, you can check the prototype of the other objects. In the console, you can see that the prototype object contains the methods which you can use with array methods. <html> <body> <script> console.log(Array.prototype); </script> <p>Please open the web console before executing the above program.</p> </body> </html> Output On running the above program, you will see the result in web console similar to the following screenshot − Updating the Native Prototype You can update the existing method or property of the native prototype object or add a new method or property to the native prototype object. Syntax You can follow the syntax below to update or add new properties or methods to the prototype object. objName.prototype.name = value In the above syntax, objName is an object whose prototype you need to update. The ”name” is a method or property name. You can assign new values or function expressions to the ”name’. Example: Updating the toLowerCase() method of the string object”s prototype The prototype of the String object contains the toLowerCase() method. Here, we update the toLowerCase() method. The updated toLowerCase() method returns the string in the uppercase. In the output, you can observe the string, which is in uppercase. In this way, you can update the functionality of the built-in methods of the object. <html> <body> <p id = “output”>After updating the string.toLowerCase() method: </p> <script> String.prototype.toLowerCase = function () { return this.toUpperCase(); } let str = “Hello World”; document.getElementById(“output”).innerHTML += str.toLowerCase(); </script> </body> </html> Output After updating the string.toLowerCase() method: HELLO WORLD You shouldn”t update the methods and properties of the native prototype object. However, you can add new as shown in the example below. Example: Adding a new method to the prototype object You can also add a new method to the Object prototype. Here, we added the firstCase() method in the object prototype. The firstCase() method returns a string after converting the string”s first character to the uppercase. <html> <body> <p id = “output”>After executing the string.firstCase() method: </p> <script> String.prototype.firstCase = function () { // First character in uppercase. Other characters in lowercase. return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase(); } let str = “hello world”; document.getElementById(“output”).innerHTML += str.firstCase(); </script> </body> </html> Output After executing the string.firstCase() method: Hello world Adding a method to the constructor function Whenever you define an object using the constructor function, you can”t add a method or property to the constructor function using its instance. So, you need to add the method to the constructor function prototype. So it can be accessible through all instances of the object. Example In the example below, the Person() is a constructor function that initializes object properties. After that, we added the display() method to the prototype of the person() function. Next, we created two instances of the Person() function and used the display() method with them. So, methods and properties added in the prototype of the object constructor can be accessed through all instances of the constructor function. <html> <body> <p id = “demo”> </p> <script> const output = document.getElementById(“demo”); function Person(id, name) { this.id = id; this.name = name; } Person.prototype.display = function () { output.innerHTML += this.id + “, ” + this.name + “<br>”; } const p1 = new Person(1, “James”); const p2 = new Person(2, “Nayan”); p1.display(); p2.display(); </script> </body> </html> Output 1, James 2, Nayan All instances of the object inherit the properties and methods from their parent”s prototype. JavaScript Prototype Chaining Simply, you can say that the prototype stores the default values of the properties. The code overrides the prototype property value if the object constructor and its prototype contain the same properties. Example In the below code, the Person() function contains the name property. We have added the name and age property in the function”s prototype. We have created the p1 object using the Person() constructor function. The value of the name property of the p1 object is ”Nayan” as the name already exists in the constructor. The value of the age property is 20, which is the same as the age property value in the prototype. <html> <body> <p id = “output”> </p> <script> function Person(id, name) { this.id = id; this.name = name; } Person.prototype.name = “John”; Person.prototype.age = 20; const p1 = new Person(1, “Adam”); document.getElementById(“output”).innerHTML = “Id: ” + p1.id + “, Name: ” + p1.name + “, Age: ” + p1.age; </script> </body> </html> Output Id: 1, Name: Adam, Age: 20 Print Page Previous Next Advertisements ”;

JavaScript – Encapsulation

JavaScript – Encapsulation ”; Previous Next What is Encapsulation? Encapsulation in JavaScript is a way to keep the related properties and methods under a single namespace by bundling them. It can be a function, a class or an object. In JavaScript, the encapsulation can be implemented using closures, classes and getters and setters. Encapsulation is a fundamental concept in Object-oriented programming languages, along with inheritance and polymorphism. JavaScript is an object oriented programming language. It is used to hide the data from the outside world and give access to required data only to improve the integrity and security of the data. What is the need for encapsulation? Let”s discuss the need for encapsulation in JavaScript via the following example. For example, you have defined the below object in your code. const car = { Brand: “Honda city”, model: “sx”, year: 2016, } Anyone can access the properties of the car object, as shown below. car.Brand Also, anyone can change the value of any property of the car object, as shown below. car.Brand = true; Here, the value of the Brand property is changed to the boolean from the string. So, it is required to secure the original data of the object and give limited access to the data to the outside world. In this situation, the concept of encapsulation comes into the picture. Different Ways to Achieve Encapsulation in JavaScript There are three different ways to achieve encapsulation. Using the function closures Using the ES6 classes Using the Getters and Setters Here, we will learn each approach for achieving encapsulation one by one. Achieving Encapsulation Using the Function Closures A JavaScript function closure is a concept allowing the inner function to access the variable defined in the outer function even after the outer function is executed. The variables defined in the outer function can”t be accessed outside its functional scope but can be accessed using the inner scope. Example In the below code, shoppingCart() function is an outer function that contains the variables and function. The outer function has its private scope. The carItems[] array is used to store the shopping cart”s items. The add() function can access the carItems[] array and add items. The remove() function checks whether the cartItems[] contains the items you need to remove. If yes, it removes the item. Otherwise, it prints the message that you can”t remove the item. The shoppingCart() function returns the object containing the add() and remove() functions. After creating a new instance of the shoppingCart() function, you can use the add() and remove() functions to manipulate the shopping cart data. <html> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); function shoppingCart() { const cartItems = []; function add(item) { cartItems.push(item); output.innerHTML += `${item.name} added to the cart. <br>`; } function remove(itemName) { const index = cartItems.findIndex(item => item.name === itemName); if (index !== -1) { const removedItem = cartItems.splice(index, 1)[0]; output.innerHTML += `${removedItem.name} removed from the cart. <br>`; } else { output.innerHTML += `Item ${itemName} not found in the cart. <br>`; } } return { add, remove, }; } // Defining items const item1 = { name: ”Car”, price: 1000000 }; const item2 = { name: ”Bike”, price: 100000 }; // Create a new Shopping cart const cart = shoppingCart(); // Adding items to the cart cart.add(item1); cart.add(item2); // Remove bike from the cart cart.remove(”Bike”); </script> </body> </html> Output Car added to the cart. Bike added to the cart. Bike removed from the cart. In this way, no one can directly access and modify the cartItems[] array. Achieving Encapsulation Using ES6 Classes and Private Variables In JavaScript, you can use classes and private variables to achieve the encapsulation. Private Variables (Fields) in JavaScript To define the private class variables, you can write a variable name followed by the ‘#’ sign. For example, ”name” is a private variable in the below code. class car { #name= “TATA”; } If you try to access the name by the instance of the class, it will give you an error that private fields can”t be accessed outside the class. To achieve encapsulation, you can define the private variables in the class and give them access to the outside world using different methods. Example In the example below, we have defined the car class. The car class contains the ”brand”, ”name”, and ”milage” private variables. The getMilage() method is defined to return the milage of the car, and the setMilage() method is used to set the milage of the method. We created the car class”s object and used the method to access and modify the private fields. If you try to access the private field of the class, the code will throw an error. You can also define more methods in the class to access and modify other private fields. <html> <body> <div id = “output1”>The car mileage is: </div> <div id = “output2”>After updating the car mileage is: </div> <script> class Car { #brand = “TATA”; // Private field #name = “Nexon”; // Private field #milage = 16; // Private field getMilage() { return this.#milage; // Accessing private field } setMilage(milage) { this.#milage = milage; // Modifying private field } } let carobj = new Car(); document.getElementById(“output1”).innerHTML += carobj.getMilage(); carobj.setMilage(20); document.getElementById(“output2”).innerHTML += carobj.getMilage(); // carobj.#milage); will throw an error. </script> </body> </html> Output The car mileage is: 16 After updating the car mileage is: 20 Achieving Encapsulation Using the Getters and Setters The JavaScript getters and setters can be defined using the get and set keywords, respectively. The getters are used to get the class properties, and setters are used to update the class properties. They are very similar to the class methods but defined using the get/set keyword followed by the method name. Example In the example below, we have defined the User class containing the three private fields named username, password, and isLoggedIn. The getters and setters named username are defined to get and set user names. Here, you can observe that name of the

JavaScript – Global Object

JavaScript – Global Object ”; Previous Next Global Objects in JavaScript The JavaScript global object allows you to access the variables, functions, objects, etc., defined in the global scope and available everywhere in the code. In the browser, a global object is named as ”window”, and in Node.js, the global object is named ”global”. However, the global object could have different names in different run-time environments. The ”globalThis” has been introduced in ECMAScript 2020, which works with most browsers and run time environments as a global object. Syntax We can follow the syntax below to use the global object to access the variables available everywhere in the JavaScript code. var a = 10; let b = window.a; // Accessing the global variable in the browser In the above syntax, variable ”a” is a global variable, as it is defined in the global scope using the var keyword. Examples Example: Accessing global variables through the global object In the below example, we have defined the ”name” variable in the global scope using the var keyword. After that, we access the name variable using the window (global) object. <html> <body> <div id = “output”>The company name is: </div> <script> var name = “Tutorialspoint”; let company = window.name; document.getElementById(“output”).innerHTML += company; </script> </body> </html> Output The company name is: Tutorialspoint Similarly, if you define the function in the global scope, you can access it anywhere using the global object. Example: Accessing the global function through the global object In the below example, we have defined the sum() function in the global scope. After that, we have defined the obj object containing the num1, num2, and sum properties. The sum properties are initialized with a value returned by the sum() function. We used the” window” object to invoke a global sum() function. So, you can access the global variable and instances anywhere in the JavaScript code using the global object. <html> <body> <p id = “output”> </p> <script> function sum(a, b) { return a + b; } const obj = { num1: 10, num2: 20, sum: window.sum(10, 20), } document.getElementById(“output”).innerHTML += “The object is: ” + JSON.stringify(obj); </script> </body> </html> Output The object is: {“num1″:10,”num2″:20,”sum”:30} If you want to make value globally accessible from the local scope, you can directly add value to the ”window” object as a property. Let”s look at the example below. Example: Making variable globally accessible from the function scope In the example below, we add the ”addition” property to the window object in the sum() function”s body to make it available everywhere. After that, we access the ”addition” property using the ”window” object. <html> <body> <div id = “output”> </div> <script> function sum(a, b) { window.addition = a + b; } sum(20, 30); document.getElementById(“output”).innerHTML = “The sum is: ” + window.addition; </script> </body> </html> Output The sum is: 50 You can also access the global variables without using the global object like a window, as the script is assigned under the object by the JavaScript scripting engine by default. However, you can use the global object to make a variable or expression global. The JavaScript global object itself contains various methods like isNaN(), decodeURI(), etc. You can access them using the global object-like window in the browser and global in Node.js. Example: Accessing pre-defined methods of the global object The JavaScript isNaN() method of the window object is used to check whether the argument passed is a number or not. If the argument is a number, it returns false. Otherwise, it returns true. <html> <body> <p id = “output”> </p> <script> let isNumer = window.isNaN(“Hello”); document.getElementById(“output”).innerHTML = “Is hello not a number? ” + isNumer; </script> </body> </html> Output Is hello not a number? true Using the JavaScript Global Object for Polyfills You can use the JavaScript global object to check whether your browser supports a particular feature. You can show a related message if the user”s browser does not support a particular feature. Look at the example below to check whether the user”s browser supports the promises. Example In the below code, we check whether the ”promise” property exists in the window object. If yes, promises are supported by the browser, and you can execute the promise. Otherwise, you can print the message that your browser doesn”t support promise. <html> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); if (window.Promise) { output.innerHTML += “Your browser supports promises”; } else { output.innerHTML += “Your browser doesn”t support promises”; } </script> </body> </html> Output Your browser supports promises The JavaScript global object only stores the truly global variables. You shouldn”t store the variable in the global object that is not global. Otherwise, it can create conflicts in your project. Print Page Previous Next Advertisements ”;

JavaScript – Array Destructuring

JavaScript – Array Destructuring ”; Previous Next Array Destructuring JavaScript Array destructuring allows us to unpack the values from array and assign them to the variables. After that, you can use the variables to access their value and use them in the code. We can perform the array structuring using the destructuring assignment. The destructuring assignment is a basically a JavaScript expression. Syntax The syntax of array destructuring assignment in JavaScript is as follows – const array = [10, 20]; const [var1, var2] = array; In the above syntax, the “array” is the original array containing 10 and 20. When you unpack the array elements, var1 contains the 10, and var2 contains the 20. Example: Basic Array Destructuring In the example below, the arr array contains 3 numeric values. After that, we used the array destructuring to unpack array elements and store them in the num1, num2, and num3 variables. <html> <body> <div id = “output1”> </div> <div id = “output2”> </div> <div id = “output3”> </div> <script> const arr = [100, 500, 1000]; const [num1, num2, num3] = arr; document.getElementById(“output1”).innerHTML = “num1: ” + num1; document.getElementById(“output2”).innerHTML = “num2: ” + num2; document.getElementById(“output3”).innerHTML = “num3: ” + num3; </script> </body> </html> Output num1: 100 num2: 500 num3: 1000 Example: Unpacking with initial N elements of the array While destructuring the array, if the left operand has fewer variables than array elements, first, N array elements get stored in the variables. The array contains 6 elements in the below code, but 2 variables exist on the left side. So, the first 2 elements of the array will be stored in the variables, and others will be ignored. <html> <body> <div id = “output1”> </div> <div id = “output2”> </div> <script> const arr = [1, 2, 3, 4, 5, 6]; const [num1, num2] = arr; document.getElementById(“output1”).innerHTML = “num1: ” + num1; document.getElementById(“output2”).innerHTML = “num2: ” + num2; </script> </body> </html> Output num1: 1 num2: 2 Skipping Array Elements While Destructuring an Array While JavaScript array destructuring, you can skip a particular array element without assigning it to a variable. Example In the below code, the arr array contains 6 numbers. We have skipped the 2nd and 4th elements. In the output, num3 is 3, and num5 is 5, as the 2nd and 4th elements are skipped. <html> <body> <div id = “output”> </div> <script> const arr = [1, 2, 3, 4, 5, 6]; const [num1, , num3, , num5] = arr; document.getElementById(“output”).innerHTML = “num1: ” + num1 + “<br>” + “num3: ” + num3 + “<br>” + “num5: ” + num5; </script> </body> </html> Output num1: 1 num3: 3 num5: 5 Array Destructuring and Rest Operator If the left operand of the destructuring assignment operator contains fewer variables than the array elements, JavaScript ignores the last remaining array elements. To solve the problem, you can use the rest operator. You can write the last variable with a rest operator in the left operand. So, the remaining array elements will be stored in the operand of the rest operator in the array format. Example In the code below, the array”s first and second elements are stored in the num1 and num2 variables. We used the rest operator with the num3 variable. So, the remaining array elements will be stored in num3 in the array format. <html> <body> <div id = “demo”> </div> <script> const arr = [1, 2, 3, 4, 5, 6]; const [num1, num2, …nums] = arr; document.getElementById(“demo”).innerHTML = “num1: ” + num1 + “<br>” + “num2: ” + num2 + “<br>” + “nums: ” + nums; </script> </body> </html> Output num1: 1 num2: 2 nums: 3,4,5,6 If you use the rest operator in the middle, all remaining array elements will be stored in the operand of the rest operator, and variables used after the rest operator will be ignored. Array Destructuring and Default Values Sometimes, an array can contain undefined values or fewer elements than the variables. In such cases, while destructuring JavaScript arrays, the variables can be initialized with the default values. Example In the below code, num1, num2, and num3 contain 10, 20, and 30 default values, respectively. The array contains only a single element. So, when we unpack the array, the num1 variable will contain the array element, num2 and num3 will contain the default values. <html> <body> <div id = “demo”> </div> <script> const arr = [1]; const [num1 = 10, num2 = 20, num3 = 30] = arr; document.getElementById(“demo”).innerHTML = “num1: ” + num1 + “<br>” + “num2: ” + num2 + “<br>” + “num3: ” + num3; </script> </body> </html> Output num1: 1 num2: 20 num3: 30 Swapping Variables Using Array Destructuring You can also swap two variables’ values using the JavaScript Array Destructuring. Example In the below code, variables a and b are initialized with 50 and 100, respectively. After that, we added variables a and b in a different order in the left and right operands. In the output, you can see the swapped values of the a and b. <html> <body> <div id = “output”> </div> <script> let a = 50, b = 100; document.getElementById(“output”).innerHTML = “Before Swapping: a = ” + a + “, b = ” + b + “<br>”; [b, a] = [a, b] document.getElementById(“output”).innerHTML += “After Swapping: a = ” + a + “, b = ” + b; </script> </body> </html> Output Before Swapping: a = 50, b = 100 After Swapping: a = 100, b = 50 Destructuring the Returned Array from the Function In real-time development, dynamic arrays are returned from the function. So, you can also destructure the returned array from the function. Example In the example below, getNums() function returns the array of numbers. We execute the getNums() function and unpack array elements in the individual variables. <html> <body> <div id = “output”> </div> <script> function getNums() { return [99, 80, 70]; } const [num1, num2, num3] = getNums(); document.getElementById(“output”).innerHTML = “num1: ” + num1 + “<br>” + “num2:

JavaScript – RegExp

Regular Expressions and RegExp Object ”; Previous Next A regular expression (RegExp) in JavaScript is an object that describes a pattern of characters. It can contain the alphabetical, numeric, and special characters. Also, the regular expression pattern can have single or multiple characters. The JavaScript RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on text. The regular expression is used to search for the particular pattern in the string or replace the pattern with a new string. There are two ways to construct the regular expression in JavaScript. Using the RegExp() constructor. Using the regular expression literal. Syntax A regular expression could be defined with the RegExp () constructor, as follows − var pattern = new RegExp(pattern, attributes); or simply var pattern = /pattern/attributes; Parameters Here is the description of the parameters − pattern − A string that specifies the pattern of the regular expression or another regular expression. attributes − An optional string containing any of the “g”, “i”, and “m” attributes that specify global, case-insensitive, and multi-line matches, respectively. Before we learn examples of regular expression, let”s learn about regular expression modifiers, Quantifiers, literal characters, etc. Modifiers Several modifiers are available that can simplify the way you work with regexps, like case sensitivity, searching in multiple lines, etc. Sr.No. Modifier & Description 1 i Perform case-insensitive matching. 2 m Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary 3 g Performs a global matchthat is, find all matches rather than stopping after the first match. Brackets Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters. Sr.No. Expression & Description 1 […] Any one character between the brackets. 2 [^…] Any one character not between the brackets. 3 [0-9] It matches any decimal digit from 0 through 9. 4 [a-z] It matches any character from lowercase a through lowercase z. 5 [A-Z] It matches any character from uppercase A through uppercase Z. 6 [a-Z] It matches any character from lowercase a through uppercase Z. The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v. Quantifiers The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags all follow a character sequence. Sr.No. Expression & Description 1 p+ It matches any string containing one or more p”s. 2 p* It matches any string containing zero or more p”s. 3 p? It matches any string containing at most one p. 4 p{N} It matches any string containing a sequence of N p”s 5 p{2,3} It matches any string containing a sequence of two or three p”s. 6 p{2, } It matches any string containing a sequence of at least two p”s. 7 p$ It matches any string with p at the end of it. 8 ^p It matches any string with p at the beginning of it. 9 ?!p It matches any string which is not followed by a string p. Examples Following examples explain more about matching characters. Sr.No. Expression & Description 1 [^a-zA-Z] It matches any string not containing any of the characters ranging from a through z and A through Z. 2 p.p It matches any string containing p, followed by any character, in turn followed by another p. 3 ^.{2}$ It matches any string containing exactly two characters. 4 <b>(.*)</b> It matches any string enclosed within <b> and </b>. 5 p(hp)* It matches any string containing a p followed by zero or more instances of the sequence hp. Literal characters The literal characters can be used with a backslash () in the regular expression. They are used to insert special characters, such as tab, null, Unicode, etc., in the regular expression. Sr.No. Character & Description 1 Alphanumeric Itself 2 The NUL character (u0000) 3 t Tab (u0009 4 n Newline (u000A) 5 v Vertical tab (u000B) 6 f Form feed (u000C) 7 r Carriage return (u000D) 8 xnn The Latin character specified by the hexadecimal number nn; for example, x0A is the same as n 9 uxxxx The Unicode character specified by the hexadecimal number xxxx; for example, u0009 is the same as t 10 cX The control character ^X; for example, cJ is equivalent to the newline character n Metacharacters A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning. For instance, you can search for a large sum of money using the ”d” metacharacter: /([d]+)000/, Here d will search for any string of numerical character. The following table lists a set of metacharacters which can be used in PERL Style Regular Expressions. Sr.No. Character & Description 1 . a single character 2 s a whitespace character (space, tab, newline) 3 S non-whitespace character 4 d a digit (0-9) 5 D a non-digit 6 w a word character (a-z, A-Z, 0-9, _) 7 W a non-word character 8 [b] a literal backspace (special case). 9 [aeiou] matches a single character in the given set 10 [^aeiou] matches a single character outside the given set 11 (foo|bar|baz) matches any of the alternatives specified Let”s learn to create regular expressions below. let exp = /tutorialspoint/i /tutorialspoint/ – It finds a match for the ”tutorialspoint” string. i – It ignores the case of the characters while matching the pattern with the string. So, it matches with ”TutoiralsPoint”, or ”TUTORIALSpoint”, etc. let exp = /d+/ d – It matches 0 to 9 digits. + – It matches one or more numeric digits. let exp = /^Hi/ ^ – It matches

JavaScript – Object Accessors

JavaScript – Object Accessors ”; Previous Next The object accessor properties in JavaScript are methods that get or set the value of an object. They are defined using the get and set keywords. Accessor properties are a powerful way to control how your objects are accessed and modified. The JavaScript object can have two kinds of properties. Data properties Accessor properties The below property is called the data properties. const obj = { key: “value”, // Data property } Object Accessor Properties In JavaScript, you can use the getters to get the object properties and setters to set the object properties. There are two keywords to define accessor properties. get − The get keyword is used to define a method to get the object property value. set − The set keyword is used to define a method to update the object property value. JavaScript Getters The getters are used to access the object properties. To define a method as getter, we use get keyword followed by method name. Follow the syntax below to define the getter. get methodName() { // Method body } obj.methodName; In the above syntax, we have defined the getters using the ”get” keyword followed by the method name. You can use the method name as an object property to get its returned value. You don”t need to write the pair of parenthesis followed by the method name to execute the getters. You can access it like the object property. Example In the example below, in the wall object, we have defined the getColor() getters. The getColor() returns the value of the color property. After that, we use the getColor() method to access the color property value of the object. <html> <body> <p id = “output”>The color of the wall is : </p> <script> const wall = { color: “brown”, get getColor() { return this.color; } } document.getElementById(“output”).innerHTML += wall.getColor; </script> </body> </html> Output The color of the wall is : brown JavaScript Setters The setters are used to update the JavaScript object properties. To define a method as setter, we use set keyword followed by method name You can follow the syntax below to define setters in the JavaScript object. set methodName(param) { // Setter method return this.color = color; } wall.methodName = “Red”; In the above syntax, the ”set” keyword is used to define the setter method. The method_name can be any valid identifier. The setter method always takes a single parameter. If you don”t pass a parameter or multiple parameters, it will give you an error. You can assign value to the setter method as you assign value to the property. Example In the example below, we have defined the setter method to set the value of the color property of the wall object. We set the ”red” value to the color property of the object using the ”setColor” setter method. <html> <body> <p id = “output”> </p> <script> const wall = { color: “brown”, set setColor(color) { return this.color = color; } } document.getElementById(“output”).innerHTML += “The color of the wall before update is : ” + wall.color + “<br>”; //updating the color of wall wall.setColor = “Red”; document.getElementById(“output”).innerHTML += “The color of the wall after update is : ” + wall.color; </script> </body> </html> Output The color of the wall before update is : brown The color of the wall after update is : Red JavaScript Object Methods vs. Getters/Setters In JavaScript, whatever you can do using the getters and setters, you can also do by defining the specific object method. The difference is that getters and setters provide simpler syntax. Let”s understand it with the help of some examples. Example In the example below, we have defined the getColor() getters method and colorMethod() object method in the wall object. Both method returns the color value. You can observe that defining and accessing getters is more straightforward than defining and accessing the object method. <html> <body> <p id = “output”> </p> <script> const wall = { color: “brown”, get getColor() { return this.color; }, colorMethod: function () { return this.color; } } document.getElementById(“output”).innerHTML += “Getting the color using the getters : ” + wall.getColor + “<br>”; document.getElementById(“output”).innerHTML += “Getting the color using the object method : ” + wall.colorMethod(); </script> </body> </html> Output Getting the color using the getters : brown Getting the color using the object method : brown Data Quality and Security The getter and setter methods can provide better data quality. Also, they are used for encapsulation to secure the object data. Let”s understand how getter and setter improve data quality and provide security via the example below. Example In the example below, the getColor() is a getter method, returning the value of the color property after converting it to the uppercase. Also, it hides the color property from users, as you can access its value using the getColor() method. <html> <body> <p id = “output”> </p> <script> const wall = { color: “Brown”, get getColor() { return this.color.toUpperCase(); } } document.getElementById(“output”).innerHTML += “Getting the color using the getters : ” + wall.getColor; </script> </body> </html> Output Getting the color using the getters : BROWN Defining getters/setters using the Object.defineProperty() You can also use the Object.defineProperty() method to add getters or setters into the object. Object.defineProperty(object, “methodName”, { keyword: function () { // Method body }, }) Using the above syntax, you can define the getter or setter same as methodName. Parameters object − It is an object where you need to add getters or setters. methodName − It is the name of the method for getters or setters. keyword − It can be ”get” or ”set” according to you want to define the getter or setter method. Example In the example below, we have added the getSize and setSize getter and setter to the object using the object.defineProperty() method. After that, we use the getSize and setSize to get and set the size, respectively. <html> <body> <p id = “demo”> </p> <script> const output =

JavaScript – this Keyword

JavaScript – this Keyword ”; Previous Next 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 OR this.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; function printNum() { 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!”; function printMessage() { 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!”; function test() { “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”); function Animal() { this.name = ”Lion”; this.age = 3; this.color = ”Brown”; } const newAnimal = new Animal(); 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); const getInnerDetails = () => { 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

JavaScript – Polymorphism

JavaScript – Polymorphism ”; Previous Next Polymorphism in JavaScript The polymorphism in JavaScript allows you to define multiple methods with the same name and different functionalities. Polymorphism is achieved by using method overloading and overriding. JavaScript does not support method overloading natively. Method overriding allows a subclass or child class to redefine a method of superclass or parent class. In this chapter, we will implement the polymorphism using the concept of method overriding. The polymorphism word is derived from the geek word polymorph. If you break the polymorph, the meaning of the ”poly” means many, and ”morph” means transforming from one state to another state. Method Overriding Before you understand the polymorphism, it is important to understand the method overriding. If you define a method with the same name in the parent and child class, the child class method overrides the parent class”s method. For example, you want to calculate the area of the different shapes. You have defined the Shape class containing the area() method. Now, you have a different class for the different shapes, and all extend the Shape class, but you can”t use the area() method of the Shape class to find the area of each shape as each geometry has a different formula to find the area. So, you need to define the area() method in each child class, override the area() method of the Shape class, and find the area of the particular shape. This way, you can create many forms of the single method. Examples Let”s understand the polymorphism and method overriding via the example below. Example 1: Demonstrating Polymorphism in JavaScript In the example below, the Shape class contains the area() method. The Circle and Rectangle, both classes, extend the Shape class. Also, the area() method is defined in the Circle and Rectangle class. There are 3 area() methods defined in the below code, but which method will invoke it depends on which class”s instance you are using to invoke the method. <html> <body> <div id = “output1”> </div> <div id = “output2”> </div> <script> class Shape { area(a, b) { return “The area of each Geometry is different! <br>”; } } class Circle extends Shape { area(r) { // Overriding the method of the Shape class return “The area of Circle is ” + (3.14 * r * r) + “<br>”; } } class Rectangle extends Shape { area(l, b) { // Overriding the method of the Shape class return “The area of Rectangle is ” + (l * b) + “<br>”; } } const circle = new Circle(); // Calling area() method of Circle class document.getElementById(“output1”).innerHTML = circle.area(5); const rectangle = new Rectangle(); // Calling area() method of Rectangle class document.getElementById(“output2″).innerHTML = rectangle.area(5, 10); </script> </body> </html> Output The area of Circle is 78.5 The area of Rectangle is 50 This way, you can define the same method with different functionalities and invoke a particular one according to the required functionalities. You can also call the parent class method in the child class using the super keyword. Let”s understand it via the example below. Example 2: Parent Class Method”s Functionality Extension in Child Class The Math and AdvanceMath class contains the mathOperations() method in the example below. In the mathOperations() method of the AdvanceMath class, we used the super keyword to invoke the mathOperations() method of the parent class. We extend the functionality of the math class”s mathOperations() method in the AdvanceMath class”s mathOperations() method. Also, when you invoke the mathOperation() method using the object of the Math class, it invokes the method of the Math class only. <html> <body> <p id = “output1”> </p> <p id = “output2”> </p> <script> class Math { mathOperations(a, b) { document.getElementById(“output1”).innerHTML = “Addition: ” + (a+b) + “<br>”; document.getElementById(“output1”).innerHTML += “Subtraction: ” + (a-b); } } class AdvanceMath extends Math { mathOperations(a, b) { super.mathOperations(a, b); document.getElementById(“output2”).innerHTML += “Multiplication: ” + (a*b) + “<br>”; document.getElementById(“output2”).innerHTML += “Division: ” + (a/b); } } const A_math = new AdvanceMath(); A_math.mathOperations(10, 5); // Calls method of AdvanceMath class </script> </body> </html> Output Addition: 15 Subtraction: 5 Multiplication: 50 Division: 2 This type of polymorphism is called runtime polymorphism, as the JavaScript engine decides which method it should execute at the run time based on which class”s instance is used. Benefits of using Polymorphism in JavaScript There are many advantages to using polymorphism in JavaScript; we have explained some of them here. Code reusability − Polymorphism allows you to reuse the code. In the second example, we have reused the code of the mathOperations() method of the math class. Extensibility − You can easily extend the current code and define new functionalities. Dynamic behaviors − You can have multiple classes containing the same method with different functionalities and call the method of the particular class dynamically at the run time. You can”t achieve the compile time polymorphism in JavaScript as you can”t overload the method. Print Page Previous Next Advertisements ”;

JavaScript – Object Destructuring

JavaScript – Object Destructuring ”; Previous Next Object Destructuring The object destructuring assignments are JavaScript expressions that allow you to unpack and assign object properties into individual variables. The name of the individual variables can be the same as the object properties or different. The object destructuring is a very useful feature when you have an object with a lot of properties and you only need a few of them. Syntax The syntax of Object Destructing assignment in JavaScript is as follows – const { prop1, popr2 } = obj; OR const { prop1: p1, prop12: p2 } = obj; // Renaming variables OR const { prop1 = default_vaule } = obj; // With Default values OR const { prop1, …prop2 } = obj; // With rest parameter In the above syntax, ”obj” is an object. The prop1 and prop2 are object properties. It covers the different use cases of object destructuring. Example: Basic Object Destructuring In the example below, the watch object contains the brand and price properties. We store the values of the object properties into the individual variables using object destructuring. You can see the brand”s value and price variable in the output, which is the same as object property values. <html> <body> <p id = “output”> </p> <script> const watch = { brand: “Titan”, price: 6000, } const {brand, price} = watch; document.getElementById(“output”).innerHTML += “The brand of the watch is ” + brand + ” and the price is ” + price; </script> </body> </html> Output The brand of the watch is Titan and the price is 6000 Example: Destructuring with less properties The code below demonstrates that you can unpack only required object properties and keep others as it is. Here, the Object contains total 4 properties. But we have unpacked only brand and price properties. <html> <body> <p id = “output”> </p> <script> const watch = { brand: “Titan”, price: 6000, color: “Pink”, dial: “Round”, } const { brand, price } = watch; document.getElementById(“output”).innerHTML = “The brand of the watch is ” + brand + ” and the price is ” + price; </script> </body> </html> Output The brand of the watch is Titan and the price is 6000 Object Destructuring and Renaming Variables In JavaScript object destructuring, it is not necessary to store the object property values in the variables with the same name as object properties. You can write a new variable name followed by a colon followed by an object property name. In this way, you can rename the object properties while destructuring the object. Example In the example below, we have stored the value of the brand property in the ”bd” variable, the color property in the ”cr” variable, and the dial property in the ”dl” variable. The values of the new variables are the same as the object properties. <html> <body> <p id = “output1”>brand: </p> <p id = “output2”>color: </p> <p id = “output3”>dial: </p> <script> const watch = { brand: “Titan”, color: “Pink”, dial: “Round”, } const { brand: bd, color: cr, dial: dl } = watch; document.getElementById(“output1”).innerHTML += bd; document.getElementById(“output2”).innerHTML += cr; document.getElementById(“output3″).innerHTML += dl; </script> </body> </html> Output brand: Titan color: Pink dial: Round Object Destructuring and Default Values In many situations, an object property may contain an undefined value, or particular property doesn”t exist in the object. If the property is undefined, JavaScript destructuring assignment allows you to initialize the variables with default values. Example In the below code, the animal object contains the name and age properties. We destructure the object and try to get the name and color property values from the object. Here, the color property doesn”t exist in the object, but we have initialized it with the default value. The output shows ”yellow” as the color variable”s value, which is the default value. <html> <body> <p id = “output1”>Animal Name: </p> <p id = “output2”>Animal Color: </p> <script> const animal = { name: “Lion”, age: 10, } const { name = “Tiger”, color = “Yellow” } = animal; document.getElementById(“output1”).innerHTML += name; document.getElementById(“output2”).innerHTML += color; </script> </body> </html> Output Animal Name: Lion Animal Color: Yellow Example In the below code, we have renamed the variables and assigned the default values to the variables. We used the colon to change the variable name and the assignment operator to assign the default values. <html> <body> <p id = “output1”>Animal Name: </p> <p id = “output2”>Animal Color: </p> <script> const animal = { name: “Lion”, age: 10, } const { name: animalName = “Tiger”, color: animalColor = “Yellow” } = animal; document.getElementById(“output1”).innerHTML += animalName; document.getElementById(“output2″).innerHTML += animalColor; </script> </body> </html> Output Animal Name: Lion Animal Color: Yellow Object Destructuring and Rest Operator The syntax of the JavaScript Rest parameter is three dots (…). It allows you to collect the remaining object properties into a single variable in the object format. Let”s understand it via the example below. Example In the below code, the nums object contains the 4 properties. While destructuring, the object value of the num1 property is stored in the num1 variable. Other remaining properties are stored in the ”numbers” variable using the rest operator. In the output, you can see that ”numbers” contains the object containing the remaining properties of the nums object. <html> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); const nums = { num1: 10, num2: 20, num3: 30, num4: 40, } const {num1, …numbers} = nums; output.innerHTML += “num1: ” + num1 + “<br>”; output.innerHTML += “numbers: ” + JSON.stringify(numbers); </script> </body> </html> Output num1: 10 numbers: {“num2″:20,”num3″:30,”num4”:40} Object Destructuring and Function Parameter You can pass the JavaScript object as a function argument. After that, you can destructure the object in the parameter of the function definition. Example In the below code, the nums object contains multiple properties, and we have passed it as an argument of the sum() function. In the function parameter, we destructure the object and use that variable inside the function body. The function body returns