JavaScript – Display Objects

JavaScript – Display Objects ”; Previous Next Displaying Objects in JavaScript There are different ways to display objects in JavaScript. Using the console.log() method, we can display the object in the web console. Sometimes developers require to display the object properties and their value in the HTML or for debugging the code. For displaying an object, we can access the different properties and display them. We can also convert the object to a JSON string and display it as a string. When you print the object like other variables in the output, it prints the ”[object Object]” as shown in the example below. In the example below, we have created a fruit object and printed it in the output. You can observe that it prints the [object Object]. <html> <body> <p id = “output”>The object is: </p> <script> const fruit = { name: “Banana”, price: 100, } document.getElementById(“output”).innerHTML += fruit; </script> </body> </html> Output The object is: [object Object] To overcome the above problem, you need to use specific approaches to display the object. Some approaches to display the JavaScript objects are as follows − Accessing the object properties Using the JSON.stringify() method Using the Object.entries() method Using the for…in loop Accessing the Object Properties In the object properties chapter, you learned different ways to access the values of the object properties. You can use the dot notation or square bracket notation to display the property values. This way, you may get all property values and display them in the output. Syntax Users can follow the syntax below to display the object by accessing properties. obj.property; OR obj[“property”]; In the above syntax, we access the property using the obj object”s dot and square bracket notation. Example In the example below, we have accessed the ”name” property of the object using the dot notation and the ”price” property using the square bracket notation. <html> <body> <p id=”output”> </p> <script> const fruit = { name: “Banana”, price: 100, } const fruitName = fruit.name; const fruitPrice = fruit[“price”]; document.getElementById(“output”).innerHTML = “The price of the ” + fruitName + ” is: ” + fruitPrice; </script> </body> </html> Output The price of the Banana is: 100 Using the JSON.stringify() Method When object contains the dynamic properties or you don”t know object properties, you can”t print properties and values using the first approach. So, you need to use the JSON.stringify() method. It converts the object into a string. Syntax Follow the syntax below to use the JSON.stringify() method to display the object. JSON.stringify(obj); You need to pass the object as a parameter of the JSON.stringify() method. Example In the example below, we have converted the fruit string into the JSON string and displayed in the output. <html> <body> <p id = “output”>The fruit object is </p> <script> const fruit = { name: “Banana”, price: 100, } document.getElementById(“output”).innerHTML += JSON.stringify(fruit); </script> </body> </html> Output The fruit object is {“name”:”Banana”,”price”:100} Using the Object.enteries() Method The Object.entries() is a static method of the Object class, allowing you to extract the properties and values in the 2D array. After that, you can use the loop to traverse the array and display each property and value pair individually. Syntax Follow the syntax below to use the Object.entries() method. Object.entries(obj); The Object.entries() method takes the object as a parameter and returns the 2D array, where each 1D array contains the key-value pair. Example In the example below, the numbers object contains the 4 properties. We used the Object.entries() method to get all entries of the object. After that, we used the for loop to traverse the object entries and display them. <html> <body> <p> Displaying the object entries</p> <p id = “output”> </p> <script> const numbers = { num1: 10, num2: 20, num3: 30, num4: 40, } for (const [key, value] of Object.entries(numbers)) { document.getElementById(“output”).innerHTML += key + “: ” + value + ” <br>”; } </script> </body> </html> Output Displaying the object entries num1: 10 num2: 20 num3: 30 num4: 40 Using the for…in Loop The for…in loop is used to traverse the iterable, and the object is one of them. Syntax Users can follow the syntax below to use the for…in loop to traverse the object and display it in the output. for (key in obj) { // Use the key to access the value } In the above syntax, obj is an object to display. In the loop body, you can access the value related to the key and print the key-value pair. Example In the example below, we used the for…in loop to traverse each key of the object and print them in the output. <html> <body> <p> Displaying Object Entries using for…in loop:</p> <p id = “output”> </p> <script> const languages = { language1: “JavaScript”, language2: “Python”, language3: “Java”, language4: “HTML”, } for (const key in languages) { document.getElementById(“output”).innerHTML += key + “: ” + languages [key] + ” <br>”; } </script> </body> </html> Output Displaying Object Entries using for…in loop: language1: JavaScript language2: Python language3: Java language4: HTML The best way to display the object is using the JSON.stringify() method. It converts the object into a flat string. Other approaches can”t be used to display the nested objects, but JSON.stringify() method can be used. Print Page Previous Next Advertisements ”;

JavaScript – TypedArray

JavaScript – The TypedArray Object ”; Previous Next What is a TypedArray? A JavaScript TypedArray is an array-like object used to store binary data. Unlike the array, the size of the TypedArray can”t be dynamic and can”t hold the values of the different data types, improving the performance of the TypedArray. A TypedArray is used in audio processing, graphics rendering, networking, etc. Why TypedArray? In other programming languages like C++, an array can contain data of only one data type, but a JavaScript array is a bit different. It can contain elements of multiple data types. So, JavaScript arrays are less efficient in dealing with binary data and when higher performance is needed. It is one of the reasons that TypedArray is introduced in JavaScript, and it is also called the array buffer. A TypedArray is the best way to handle binary data while maintaining the memory. TypedArray Objects Here are the types of TypedArray objects available to store the data of the 8, 16, 32, or 64-bit data. You can choose any object to create a TypedArray according to the data you need to store. Sr. No. TypedArray Data Type Range Example 1 Int8Array 8-bit two”s complement Signed integer (byte) -28 to 127 new Int8Array([92, 17, -100]) 2 Uint8Array 8-bit Unsigned integer 0 to 255 new Uint8Array([132, 210, 0]) 3 Uint8ClampedArray 8-bit Unsigned integer 0 to 255 new Uint8ClampedArray([90, 17, 70]) 4 Int16Array Short integer -32768 to 32767 new Int16Array([1000, -2000, 150]) 5 Uint16Array Unsigned short int 0 to 65535 new Uint16Array([50, -6535, 12000]) 6 Int32Array Signed long integer -2147483648 to 2147483647 new Int32Array([1000000, -2000000, 9876]) 7 Uint32Array Unsigned long integer 0 to 4294967295 new Uint32Array([100, 42967295, 0]) 8 Float32Array Float (7 significant digits) ±1.2×10^-38 to ±3.4×10^38 new Float32Array([3.134, 1.618, -0.5]) 9 Float64Array Double (16 significant digits) ±5.0×10^-324 to ±1.8×10^308 new Float64Array([2.78, -12.35, 99.9]) 10 BigInt64Array Big signed integer -2^63 to 2^63 − 1 new BigInt64Array([-9071954740991n, 9719925474991n]) 11 BigUint64Array Big unsigned integer 0 to 2^64 – 1 new BigUint64Array([0n, 18446744709551615n]) A TypedArray doesn”t support the methods like push(), pop, etc., but supported properties and methods are listed below. TypedArray Properties Here is a list of the properties of the TypedArray object along with their description − Sr.No. Property & Description 1 Constructor It returns an array buffer constructor. 2 byteLength It returns the byte length of the TypedArray. 3 maxByteLength It returns the maximum byte length to expand the size of the TypedArray. 4 resizable To check whether the TypedArray is resizable. TypedArray Static Methods Here is a list of the static methods of the TypedArray object along with their description − Sr.No. Methods Description 1 from() It returns a new Array instance. 2 of() It returns a new Array instance. TypedArray Instance Methods Here is a list of the instance methods of the TypedArray object along with their description − TypedArray instance methods Sr.No. Methods Description 1 at() It returns an element in the typed array that matches the given index. 2 copyWithin() It returns a modified TypedArray without changing the length of the original TypedArray. 3 entries() It returns a new array iterable object. 4 every() It returns true if all elements in the typed array pass the test implemented by the callback function, and false otherwise. 5 fill() It returns the modified typed array, that is filled with the specified value. 6 filter() It returns a new copy of a typed array that includes only the elements that pass the test. 7 find() It returns the first element is TypedArray that satisfied the provided test function, ”undefined” otherwise. 8 findIndex() It returns an index of the first element is TypedArray that satisfied the provided test function, ”-1” otherwise. 9 findLast() It returns the last element in the typed array that satisfies the provided testing function, ”undefined” if not found. 10 findLastIndex() It returns the last element in the typed array that passes the test, -1 if not found. 11 forEach() It returns none(undefined). 12 includes() It returns ”true” if searchElement is found in the typed array; ”false” otherwise. 13 indexof() It returns the first index of the searchElement. 14 join() It returns a string by joining all the elements of a typed array. 15 Keys() It returns a new iterable iterator object. 16 lastIndexof() It returns the last index of the searchElement in a typed array. If the search element is not present, it returns -1. 17 map() It returns a new typed array by executing the callback function on each element. 18 reduce()

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

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.

JavaScript – Classes

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

JavaScript – Default Parameters

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