JavaScript – The Symbol Object ”; Previous Next JavaScript Symbol In JavaScript, Symbol is a primitive data type and it was introduced in ECMAScript 6 (ES6). It can be created using the ”Symbol” constructor. Symbols are immutable and unique, unlike to other primitive data types like strings or numbers. They are especially helpful in situations where a unique identifier is required since they offer a way to create private object properties and avoid naming conflicts. Here, we have listed the properties and methods related to the symbol. The points given below you should keep in mind while using the symbol. Each symbol contains unique values. The symbol is immutable. It means you can”t update the value of the symbol. Symbols are used to define unique object properties. The type of the symbol can”t be changed. Syntax You can follow the syntax below to create a new symbol using the Symbol() function. − const sym = Symbol([description]); Here description is an optional parameter. It specifies the symbol description, which you can access using the ”description” property. Symbol Properties In the following table, we have listed all the properties of Symbol − Sr.No. Name & Description 1 description To get an optional description of the symbol object. 2 asyncIterator It changes the object to async iterable. 3 hasInstance To check whether the constructor object counts the object as its instance. 4 isConcatSpreadable It determines that while using the array.concat() method array should be concatenated as an object or flattened array. 5 iterator Returns an iterator of the symbol. 6 match Matches the regular expression with the string. 7 matchAll Returns all matches of the regular expression with the string. 8 replace To replace a substring. 9 search To get an index of the matches value. 10 species To create a derived object. 11 split It specifies the method that splits string from the indices where regular expression matches. 12 toStringTag To create a default string description for the object. Symbol Methods In the following table, we have listed all the methods of Symbol − Sr.No. Name & Description 1 for() To search for a given symbol. 2 keyFor() To retrieve a key from the global symbol registry. 3 toString() To convert the symbol into the string. 4 valueOf() To get the primitive value of the symbol object. Examples Example: Creating a Symbol In the example below, We used the Symbol() function to create a new symbol. Also, we have passed the string argument while defining the sym2 symbol. You can observe the type of the ”sym1”, which is ”symbol”, a primitive value. <html> <body> <p id=”output”></p> <script> const sym1 = Symbol(); document.getElementById(“output”).innerHTML = “The sym1 is: ” + sym1.toString() + “<br>” + “The type of sym1 is: ” + typeof sym1 + “<br>”; const sym2 = Symbol(“description”); document.getElementById(“output”).innerHTML += “The sym2 is: ” + sym2.toString(); </script> </body> </html> Output When we execute the above script, it will generate an output consisting of the text displayed on the webpage. The sym1 is: Symbol() The type of sym1 is: symbol The sym2 is: Symbol(description) Example: Accessing Symbol Description Let”s look at the following example, where we are going to use the .description to get the description of the symbol. <html> <body> <p id=”output”></p> <script> const sym = Symbol(“Welcome to Tutorials Point…”); document.getElementById(“output”).innerHTML = “The sym description of the symbol is : ” + sym.description; </script> </body> </html> Output On executing the above script, the output window will pop up, displaying the text on the webpage. The sym description of the symbol is : Welcome to Tutorials Point… Example: Each Symbol is Unique In the example below, we have defined the sym1 and sym2 symbols. After that, we compare both variables and print the message accordingly. Both symbols look similar but are different, which you can see in the output. <html> <body> <p id=”output”></p> <script> const sym1 = Symbol(); const sym2 = Symbol(); if (sym1 == sym2) { document.getElementById(“output”).innerHTML += “Sym1 and Sym2 are equal.”; } else { document.getElementById(“output”).innerHTML += “Sym1 and Sym2 are not equal.”; } </script> </body> </html> Output After executing, it returns a text indicating that the both the symbols are not equal. Sym1 and Sym2 are not equal. Example: Using Symbol as an Object Key The main purpose of the symbol is to use it as an object key. Here, we have used the ”objId” symbol as a key. When we print the object by converting it to string or traversing the object properties, it won”t print the symbol. So, the symbol can help developers to make object properties private. <html> <body> <p id=”output”>The object is: </p> <script> const objId = Symbol(); const person = { name: “John Doe”, age: 30, [objId]: “abcd123”, } document.getElementById(“output”).innerHTML += JSON.stringify(person); </script> </body> </html> Output If we execute the above program, it will generate an output consisting of the text displayed on the webpage. The object is: {“name”:”John Doe”,”age”:30} Benefits of using Symbols Here, we have explained the benefits of using symbols in real-time development. Unique property keys − Each symbol is unique, even if its description is different. So, you can use the symbol as a
Category: javascript
JavaScript – Inheritance
JavaScript – Inheritance ”; Previous Next Inheritance in JavaScript The concept of inheritance in JavaScript allows the child class to inherit the properties and methods of the parent class. Inheritance is also a fundamental concept of object-oriented programming like encapsulation and polymorphism. Sometimes, you must add the properties and methods of the one class into another. For example, you have created a general class for the bike containing the same properties and methods for each bike. After that, you create a separate class for the bike “Honda”, and you need to add all properties and methods to the “Honda” class. You can achieve it using inheritance. Before ECMAScript 6 (ES6), the object”s prototype was used for inheritance, but in ES6, the ”extends” keyword was introduced to inherit classes. The following terminologies are used in this chapter. Parent class − It is a class whose properties are inherited by other classes. Child class − It is a class that inherits the properties of the other class. JavaScript Single Class Inheritance You can use the ”extends” keyword to inherit the parent class properties into the child class. In single class inheritance only a single class inherits the properties of another class. Syntax You can follow the syntax below for the single-class inheritance. class childClass extends parentClass { // Child class body } In the above syntax, you can replace the ”childClass” with the name of the child class and ”parentClass” with the name of the parent class. Example: Single Class Inheritance In the example below, the ”Bike” class is a parent class, and the ”Suzuki” class is a child class. The suzuki class inherits the properties of the Bike class. The Bike class contains the constructor() method initializing the gears property and the getGears() method returning the value of the gears property. The suzuki class contains the constructor() method to initialize the brand property and getBrand() method, returning the value of the brand property. We have created an object of the ”suzuki” class. Using the ”suzuki” class instance, we invoke the getBrand() and getGears() methods. <html> <body> <div id = “output1”>The brand of the bike is: </div> <div id = “output2”>Total gears in the bike is: </div> <script> // Parent class class Bike { constructor() { this.gear = 5; } getGears() { return this.gear; } } // Child class class suzuki extends Bike { constructor() { super(); this.brand = “Yamaha” } getBrand() { return this.brand; } } const suzukiBike = new suzuki(); document.getElementById(“output1”).innerHTML += suzukiBike.getBrand(); document.getElementById(“output2″).innerHTML += suzukiBike.getGears(); </script> </body> </html> Output The brand of the bike is: Yamaha Total gears in the bike is: 5 In this way, you can use the properties and methods of the parent class through the instance of the child class. JavaScript super() Keyword In the above example, we have initialized the ”gear” property of the Bike class with a static value. In real life, you need to initialize it with the dynamic value according to the model of the bike. Now, the question is how to initialize the properties of the parent class from the child class. The solution is a super() keyword. The super() keyword is used to invoke the method or access the properties of the parent class in the child class. By default, the super() keyword invokes the constructor function of the parent class. You can also pass the parameters to the super() keyword to pass it to the constructor of the parent class. Example: Using super() keyword to initialize the parent class properties In the example below, suzuki class extends the Bike class. The Bike class contains the constructor, taking gears as parameters and, using it, initializes the gears property. The ”suzuki” class also contains the constructor, taking a brand and gears as a parameter. Using the brand parameter, it initializes the brand property and passes the gears parameter as an argument of the super() keyword. After that, we create an object of the ”suzuki” class and pass the brand and gears as an argument of the constructor. You can see the dynamic value of the brand and gear property in the output. <html> <body> <div id = “output1”>The brand of the bike is: </div> <div id = “output2”>Total gears in the bike is: </div> <script> // Parent class class Bike { constructor(gears) { this.gears = gears; } } // Child class class suzuki extends Bike { constructor(brand, gears) { super(gears); this.brand = brand; } } const suzukiBike = new suzuki(“Suzuki”, 4); document.getElementById(“output1”).innerHTML += suzukiBike.brand; document.getElementById(“output2″).innerHTML += suzukiBike.gears; </script> </body> </html> Output The brand of the bike is: Suzuki Total gears in the bike is: 4 In this way, you can dynamically initialize the properties of the parent class from the child class. JavaScript Multilevel Inheritance Multilevel inheritance is a type of inheritance in JavaScript. In multilevel inheritance, one class inherits the properties of another class, and other classes inherit current class properties. Syntax Users can follow the syntax below for the multilevel inheritance. class A { } class B extends A { } class C extends B { } In the above syntax, the C class inherits the B class, and the B class inherits the A class. Example In the example below, the Honda class inherits the Bike class. The Shine class inherits the Honda class. We use the super() keyword in each class to invoke the parent class”s constructor () and initialize its properties. We are accessing the properties of the Bike class using the instance of the Shine class, as it indirectly inherits the properties of the Bike class. <html> <body> <p id = “output”> </p> <script> // Parent class class Bike { constructor(gears) { this.gears = gears; } } // Child class class Honda extends Bike { constructor(brand, gears) { super(gears); this.brand = brand; } } class Shine extends Honda { constructor(model, brand, gears) { super(brand, gears); this.model = model; } } const newBike = new Shine(“Shine”, “Honda”, 5); document.getElementById(“output”).innerHTML = `The ${newBike.model} model of the ${newBike.brand} brand has total ${newBike.gears} gears.`;
JavaScript – For…in
JavaScript – For…in Loop ”; Previous Next The for…in Loop The for…in loop in JavaScript is used to loop through an object”s properties. The JavaScript for…in loop is a variant of the for loop. The for loop can”t be used to traverse through the object properties. So, the for…in loop is introduced to traverse through all object properties. As we have not discussed Objects yet, you may not feel comfortable with this loop. But once you understand how objects behave in JavaScript, you will find this loop very useful. The for…in loop in JavaScript can also be used to iterate through the elements of an array. However, it is not recommended to do this as this is less efficient than using a for…of loop. Syntax The syntax of for…in loop in JavaScript is as follows − for (variableName in object) { statement or block to execute } Parameters variableName − It is a property name (key) of the object. in − It is an ”in” operator in JavaScript. object − It is the object to traverse. In each iteration, one property from object is assigned to variableName and this loop continues till all the properties of the object are exhausted. Examples Try the following examples to implement ”for-in” loop. Example: Iterate through object properties In the example below, the car object contains various properties. We used the for…in loop to traverse through each key of the object. In the output, we can see that it prints the key and its value. We use the ”[]” (member of) operator to access the value of the key from the object. <html> <head> <title> JavaScript – for…in loop </title> </head> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); let car = { brand: “OD”, model: “Q7”, color: “Black”, } for (key in car) { output.innerHTML += key + ” -> ” + car[key] + “<br>”; } </script> </body> </html> Output brand -> OD model -> Q7 color -> Black Example: Iterating over a string In JavaScript, the string is an object. So, we can use the for…in loop to traverse through each character of the string. The index of the character is the key, and the character is a value. The code prints the index and character in the output. <html> <head> <title> JavaScript – for…in loop </title> </head> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); let str = “Hello”; for (key in str) { output.innerHTML += key + ” -> ” + str[key] + “<br>”; } </script> </body> </html> Output 0 -> H 1 -> e 2 -> l 3 -> l 4 -> o Exampl: Iterating over an array In JavaScript, the array is also an object. So, the for…in loop can be used to traverse through array elements. Like a string, the index is a key, and the array element is a value for the key. The below code prints the array index and its value in the output. <html> <head> <title> JavaScript – for…in loop </title> </head> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); let array = [“Hi”, “Hello”, 900, 23, true, “JavaScript”]; for (key in array) { output.innerHTML += key + ” -> ” + array[key] + “<br>”; } </script> </body> </html> Output 0 -> Hi 1 -> Hello 2 -> 900 3 -> 23 4 -> true 5 -> JavaScript Example: Update value of each property of an object In the example below, we traverse each key of the object and update its value to null. In the output, the code prints the object keys with null values. So, the for…in loop can also be used to update all or particular property values of the object. <html> <head> <title> JavaScript – for…in loop </title> </head> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); let car = { brand: “OD”, model: “Q7”, color: “Black”, } for (key in car) { car[key] = null; } output.innerHTML += “The updated object is – ” + JSON.stringify(car); </script> </body> </html> Output The updated object is – {“brand”:null,”model”:null,”color”:null} Example: Iterating the Browser”s Navigator Object Try the following example to implement ”for-in” loop. It prints the web browser’s Navigator object. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(“demo”); var aProperty; output.innerHTML = “Navigator Object Properties<br> “; for (aProperty in navigator) { output.innerHTML += aProperty; output.innerHTML += “<br>”; } output.innerHTML += “Exiting from the loop!”; </script> </body> </html> Output Navigator Object Properties vendorSub productSub vendor maxTouchPoints userActivation doNotTrack geolocation connection plugins mimeTypes pdfViewerEnabled webkitTemporaryStorage webkitPersistentStorage hardwareConcurrency cookieEnabled appCodeName appName appVersion platform product userAgent language languages onLine webdriver getBattery getGamepads javaEnabled sendBeacon vibrate scheduling bluetooth clipboard credentials keyboard managed mediaDevices storage serviceWorker wakeLock deviceMemory ink hid locks mediaCapabilities mediaSession permissions presentation serial virtualKeyboard usb xr userAgentData canShare share clearAppBadge setAppBadge getInstalledRelatedApps getUserMedia requestMIDIAccess requestMediaKeySystemAccess webkitGetUserMedia registerProtocolHandler unregisterProtocolHandler Exiting from the loop! Print Page Previous Next Advertisements ”;
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 – Strings
JavaScript – Strings ”; Previous Next The String object in JavaScript lets you work with a series of characters; it wraps JavaScript”s string primitive data type with a number of helper methods. As JavaScript automatically converts between string primitives and String objects, you can call any of the helper methods of the String object on a string primitive. The string is a sequence of characters containing 0 or more characters. For example, ”Hello” is a string. Syntax JavaScript strings can be created as objects using the String() constructor or as primitives using string literals. Use the following syntax to create a String object − var val = new String(value); The String parameter, value is a series of characters that has been properly encoded. We can create string primitives using string literals and the String() function as follows − str1 = ”Hello World!”; // using single quote str2 = “Hello World!”; // using double quote str3 = ”Hello World”; // using back ticks str4 = String(”Hello World!”); // using String() function JavaScript String Object Properties Here is a list of the properties of String object and their description. Sr.No. Property Description 1 constructor Returns a reference to the String function that created the object. 2 length Returns the length of the string. 3 prototype The prototype property allows you to add properties and methods to an object. JavaScript String Object Methods Here is a list of the methods available in String object along with their description. Static Methods The static methods are invoked using the ”String” class itself. Sr.No. Property Description 1 fromCharCode() Converts the sequence of UTF-16 code units into the string. 2 fromCodePoint() Creates a string from the given sequence of ASCII values. Instance Methods The instance methods are invoked using the instance of the String class. Sr.No. Method Description 1 at() Returns the character from the specified index. 2 charAt() Returns the character at the specified index. 3 charCodeAt() Returns a number indicating the Unicode value of the character at the given index. 4 codePointAt() Returns a number indicating the Unicode value of the character at the given index. 5 concat() Combines the text of two strings and returns a new string. 6 endsWith() Checks whether the string ends with a specific character or substring. 7 includes() To check whether one string exists in another string. 8 indexOf() Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found. 9 lastIndexOf() Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. 10 localeCompare() Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. 11 match() Used to match a regular expression against a string. 12 matchAll() Used to match all occurrences of regular expression patterns in the string. 13 normalize() To get the Unicode normalization of the string. 14 padEnd() To add padding to the current string with different strings at the end. 15 padStart() To add padding to the current string with different strings at the start. 16 raw() Returns a raw string form of a given template literal. 17 repeat() To get a new string containing the N number of copies of the current string. 18 replace() Used to find a match between a regular expression and a string and replace the matched substring with a new one. 19 replaceAll() Used to find a match between a regular expression and a string and replace all the matched substring with a new one. 20 search() Executes the search for a match between a regular expression and a specified string. 21 slice() Extracts a section of a string and returns a new string. 22 split() Splits a String object into an array of strings by separating the string into substrings. 23 substr() Returns the characters in a string beginning at the specified location through the specified number of characters. 24 substring() Returns the characters in a string between two indexes into the string. 25 toLocaleLowerCase() The characters within a string are converted to lowercase while respecting the current locale. 26 toLocaleUpperCase() The characters within a string are converted to the upper case while respecting the current locale. 27 toLowerCase() Returns the calling string value converted to lowercase. 28 toString() Returns a string representing the specified object. 29 toUpperCase() Returns the calling string value converted to uppercase. 30 toWellFormed() Returns a new string that is a copy of this string. 31 trim() It removes white spaces from both ends. 32 trimEnd() It removes white spaces
JavaScript – Static Methods
JavaScript – Static Methods ”; Previous Next What are Static Methods? A static method in JavaScript is defined using the static keyword followed by the method name. You can execute the static method by taking the class name as a reference rather than an instance of the class. The main benefit of the static method is that it can be used to create a utility function that doesn”t require the instance of the class for the execution. For example, a Math object contains various static methods, which we can invoke through Math class directly. Also, you can use static methods to add all related methods under a single namespace. Furthermore, static methods give better performance than the regular class methods due to memory optimization. In the following syntax, we define a static method called getSize() in the class called Table − class Table { static getSize() { // Static method return “10 x 10″; } } Table.getSize(); // Static method invocation In the above syntax, getSize() is a static method. We used the class name to execute the getSize() method. Examples Let”s understand the JavaScript static methods with the help of some examples of difference use-cases − Example: Static Method In the example below, printSize() is a static method, and getSize() is a regular method in the table class. You can see that printSize() method is invoked using the table class name, and getSize() method is executed using the class instance. So, the class can contain static and non-static both methods. <html> <body> <p id = “demo”> </p> <script> const output = document.getElementById(“demo”); class Table { static printSize() { return “The size of the table is: 20 x 20 <br>”; } getColor() { return “Black”; } } output.innerHTML = Table.printSize(); // Static method execution const tableObj = new Table(); output.innerHTML += “The color of the table is: ” + tableObj.getColor(); </script> </body> </html> Output The size of the table is: 20 x 20 The color of the table is: Black The single class can also contain multiple static methods. Example: Multiple Static Methods In the below code, the table class contains the printSize() and getSize() static methods. Both methods are executed by taking the class name as a reference. <html> <body> <p id = “output”> </p> <script> class Table { static printSize() { return “The size of the table is 20 x 20 <br>”; } static getColor() { return “The color of the table is Pink”; } } document.getElementById(“output”).innerHTML = Table.printSize() + “br” + Table.getColor(); </script> </body> </html> Output The size of the table is 20 x 20 brThe color of the table is Pink A single class can contain multiple static methods with the same name. When you execute the static method with the same name, it executes the last method. Example: Static Methods with the Same Name In the example below, the table class contains the duplicate printSize() method. In the output, you can observe that the code executes the second printSize() method. <html> <body> <p id = “output”> </p> <script> class Table { static printSize() { return”The size of the table is: 20 x 20 <br>”; } static printSize() { return “The size of the table is: 30 x 30 <br>”; } } document.getElementById(“output”).innerHTML = Table.printSize(); // Static method execution </script> </body> </html> Output The size of the table is: 30 x 30 You can also execute the static method of the class in the constructor. You can use this keyword followed by the constructor keyword followed by the static method name to execute the static method in the constructor. Example: Static Method Execution in the Constructor In the example below, the Num class contains the getSqrt() static method. We have executed the getSqrt() method in the constructor. Whenever you create a new object of the Num class, it will store the square root of the number in the ”sqrt” property of the class. <html> <body> <p id = “output”>The square root of the 10 is: </p> <script> class Num { constructor(a) { // Static method execution this.sqrt = this.constructor.getSqrt(a); } static getSqrt(a) { return a * a; } } const num1 = new Num(10); document.getElementById(“output”).innerHTML += num1.sqrt; </script> </body> </html> Output The square root of the 10 is: 100 You can also execute the static method in the non-static method. You need to use the class name as a reference to execute the static method in the non-static method. Example: Static Method Execution in Non-Static Method In the example below, getSqrt() is a static method, and printSqrt() is a regular class method. In the printSqrt() method, we execute the getSqrt() method. We used the instance of the Num class to execute the printSqrt() method. <html> <body> <p id = “demo”> </p> <script> const output = document.getElementById(“demo”); class Num { static getSqr(a) { return a * a; } printSqr(a) { output.innerHTML += “The square of ” + a + ” is: ” + Num.getSqr(a) + “<br>”; } } const num1 = new Num(); num1.printSqr(6); </script> </body> </html> Output The square of 6 is: 36 Print Page Previous Next Advertisements ”;
JavaScript – Date
JavaScript – Date ”; Previous Next The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ) as shown below. Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object using either local time or UTC (universal, or GMT) time. The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so JavaScript can represent the date and time till the year 275755. Syntax You can use any of the following syntaxes to create a Date object using the Date() constructor − new Date( ) new Date(milliseconds) new Date(datestring) new Date(year,month,date[,hour,minute,second,millisecond ]) Note − Parameters in the brackets are always optional. Parameters No Argument − With no arguments, the Date() constructor creates a Date object set to the current date and time. milliseconds − When one numeric argument is passed, it is taken as the internal numeric representation of the date in milliseconds, as returned by the getTime() method. For example, passing the argument 5000 creates a date that represents five seconds past midnight on 1/1/70. datestring − When one string argument is passed, it is a string representation of a date in the format accepted by the Date.parse() method. 7 agruments − To use the last form of the constructor shown above. Here is a description of each argument − year − Integer value representing the year. For compatibility (in order to avoid the Y2K problem), you should always specify the year in full; use 1998 rather than 98. month − Integer value representing the month, beginning with 0 for January to 11 for December. date − Integer value representing the day of the month. hour − Integer value representing the hour of the day (24-hour scale). minute − Integer value representing the minute segment of a time reading. second − Integer value representing the second segment of a time reading. millisecond − Integer value representing the millisecond segment of a time reading. Return Value It returns the date string containing day, month, date, year, hours, minutes, seconds, and timezone, as shown below. Wed Aug 09 2023 09:24:03 GMT+0530 (India Standard Time) JavaScript Date Reference In JavaScript, the Date object provides methods for creating, manipulating, and formatting dates and times. Here, we have listed all the methods present in Date class − JavaScript Date Methods Here is a list of the methods used with Date and their description. Date Static Methods These methods are invoked using the Date object − Sr.No. Name & Description 1 Date.parse() Parses a string representation of a date and time and returns the internal millisecond representation of that date. 2 Date.UTC() Returns the millisecond representation of the specified UTC date and time. Date Methods These methods are invoked using the instance of the Date object − Sr.No. Name & Description 1 getDate() Returns the day of the month for the specified date according to local time. 2 getDay() Returns the day of the week for the specified date according to local time. 3 getFullYear() Returns the year of the specified date according to local time. 4 getHours() Returns the hour in the specified date according to local time. 5 getMilliseconds() Returns the milliseconds in the specified date according to local time. 6 getMinutes() Returns the minutes in the specified date according to local time. 7 getMonth() Returns the month in the specified date according to local time. 8 getSeconds() Returns the seconds in the specified date according to local time. 9 getTime() Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. 10 getTimezoneOffset() Returns the time-zone offset in minutes for the current locale. 11 getUTCDate() Returns the day (date) of the month in the specified date according to universal time. 12 getUTCDay() Returns the day of the week in the specified date according to universal time. 13 getUTCFullYear() Returns the year in the specified date according to universal time. 14 getUTCHours() Returns the hours in the specified date according to universal time. 15 getUTCMilliseconds() Returns the milliseconds in the specified date according to universal time. 16 getUTCMinutes() Returns the minutes in the specified date according to universal time. 17 getUTCMonth() Returns the month in the specified date according to universal time. 18 getUTCSeconds() Returns the seconds in the specified date according to universal time. 19 setDate() Sets the day of the month for a specified date according to local time. 20 setFullYear() Sets the full year for a specified date according to local time. 21 setHours() Sets the hours for a specified date according to local time. 22 setMilliseconds() Sets the milliseconds for a specified date according to local
JavaScript – Smart Function Parameters ”; Previous Next The concept of smart function parameters in JavaScript is a way to make a function adaptable to different use cases. It allows the function to handle the different kinds of arguments passed to it while invoking it. In JavaScript, the function is an important concept for reusing the code. In many situations, we need to ensure the function is flexible to handle different use cases. Here are different ways to define a function with smart parameters. Default Function Parameters In JavaScript, the use of default function parameters is a way to handle the undefined argument values or arguments that haven”t passed to the function during invocation of the function. In the below code snippet, we set default values of the parameters, a and b to 100 and 50. function division (a = 100, b = 50) { // Function body } Example In the below code, the division() function returns the division of the parameters a and b. The default value of parameter a is 100, and parameter b is 50 whenever you want to pass any argument or pass an undefined argument, parameters with initialized with their default value which you can observe from the values printed in the output. <html> <head> <title> JavaScript – Default parameters </title> </head> <body> <p id = “output”> </p> <script> function division(a = 100, b = 50) { return a / b; } document.getElementById(“output”).innerHTML = division(10, 2) + “<br>” + division(10, undefined) + “<br>” + division(); </script> </body> </html> Output 5 0.2 2 JavaScript Rest Parameter When the number of arguments that need to pass to the function is not fixed, you can use the rest parameters. The JavaScript rest parameters allow us to collect all the reaming (rest) arguments in a single array. The rest parameter is represented with three dots (…) followed by a parameter. Here this parameter works as the array inside the function. Syntax Follow the below syntax to use the rest parameters in the function declaration. function funcName(p1, p2, …args) { // Function Body; } In the above syntax, ”args” is rest parameter, and all remaining arguments will be stored in the array named args. Example In the example below, the sum() function returns the sum of all values passed as an argument. We can pass an unknown number of arguments to the sum() function. The function definition will collect all arguments in the ”nums” array. After that, we can traverse the ”nums” array in the function body and calculate the sum of all argument values. The sum() function will also handle the 0 arguments also. <html> <head> <title> JavaScript – Rest parameters </title> </head> <body> <p id = “demo”> </p> <script> function sum(…nums) { let totalSum = 0; for (let p = 0; p < nums.length; p++) { totalSum += nums[p]; } return totalSum; } document.getElementById(“demo”).innerHTML = sum(1, 5, 8, 20, 23, 45) + “<br>” + sum(10, 20, 30) + “<br>” + sum() + “<br>”; </script> </body> </html> Output 102 60 0 Note – You should always use the rest parameter as a last parameter. JavaScript Destructuring or Named parameters You can pass the single object as a function argument and destructuring the object in the function definition to get only the required values from the object. It is also called the named parameters, as we get parameters based on the named properties of the object. Syntax Follow the below syntax to use the destructuring parameters with the function. function funcName({ prop1, prop2, … }) { } In the above syntax, prop1 and prop2 are properties of the object passed as an argument of the function funcName. Example In the example below, we have defined the ”watch” object containing three properties and passed it to the printWatch() function. The printWatch() function destructuring the object passed as an argument and takes the ”brand” and ”price” properties as a parameter. In this way, you can ignore the arguments in the function parameter which are not necessary. <html> <head> <title> JavaScript – Parameter Destructuring </title> </head> <body> <p id = “output”> </p> <script> function printWatch({ brand, price }) { return “The price of the ” + brand + “”s watch is ” + price; } const watch = { brand: “Titan”, price: 10000, currency: “INR”, } document.getElementById(“output”).innerHTML = printWatch(watch); </script> </body> </html> Output The price of the Titan”s watch is 10000 The above three concepts give us flexibility to pass the function arguments. Print Page Previous Next Advertisements ”;
JavaScript – Arrays
JavaScript – Array ”; Previous Next The JavaScript Array object lets you store multiple values in a single variable. An array is used to store a sequential collection of multiple elements of same or different data types. In JavaScript, arrays are dynamic, so you don’t need to specify the length of the array while defining the array. The size of a JavaScript array may decrease or increase after its creation. Syntax Use the following syntax to create an array object in JavaScript − const arr = new Array(val1, val2, val3, …, valN) Parameters val1, val2, val3, …, valN − It takes multiple values as an argument to initialize an array with them. Return value It returns an array object. Note − When you pass the single numeric argument to the Array() constructor, it defines the array of argument length containing the undefined values. The maximum length allowed for an array is 4,294,967,295. You can add multiple comma separated elements inside square brackets to create an array using the array literal − const fruits = [ “apple”, “orange”, “mango” ]; You will use ordinal numbers to access and to set values inside an array as follows. fruits[0] is the first element fruits[1] is the second element fruits[2] is the third element JavaScript Array Reference In JavaScript, the Array object enables storing collection of multiple elements under a single variable name. It provides various methods and properties to perform operations on an array. Here, we have listed the properties and methods of the Array class. JavaScript Array Properties Here is a list of the properties of the Array object along with their description − Sr.No. Name & Description 1 constructor Returns a reference to the array function that created the object. 2 length Reflects the number of elements in an array. JavaScript Array Methods Here is a list of the methods of the Array object along with their description − Array Static methods These methods are invoked using the Array class itself − Sr.No. Name & Description 1 from() Creates a shallow copy of the array. 2 isArray() Returns boolean values based on the argument is an array. 3 Of() Creates an array from multiple arguments. Array instance methods These methods are invoked using the instance of the Array class − Sr.No. Name & Description 1 at() To get element from the particular index. 2 concat() Returns a new array comprised of this array joined with another array (s) and/or value(s). 3 copyWithin() To Copy part of the array into the same array at different locations. 4 entries() To get each entry of the array. 5 every() Returns true if every element in this array satisfies the provided testing function. 6 fill() To fill the array with static values. 7 filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. 8 find() To find an element satisfying the condition. 9 findIndex() To find an index of the element satisfying the condition. 10 findLast() To find an element satisfying the condition from the last. 11 findLastIndex() To find an index of the element satisfying the condition from the last. 12 flat() To flatten the array. 13 flatMap() To get a new array after flattening the array. 14 forEach() Calls a function for each element in the array. 15 Includes() Returns a boolean value if the array contains the specific element. 16 indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. 17 join() Joins all elements of an array into a string. 18 Keys() Returns an array iterator containing the key for each array element. 19 lastIndexOf() Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found. 20 map() Creates a new array with the results of calling a provided function on every element in this array. 21 pop() Removes the last element from an array and returns that element. 22 push() Adds one or more elements to the end of an array and returns the new length of the array. 23 reduce() Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value. 24 reduceRight() Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value. 25 reverse() Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first. 26 shift() Removes the first element from an array and returns that element. 27 slice() Extracts a section of an array and returns a new array.