JavaScript – Object Methods ”; Previous Next JavaScript Object Methods JavaScript object methods are object properties that contains function definitions. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property”s value can be a function; in that case the property is known as a method. You can either directly add a method to the object or add it as a property value. The method can also take the parameters and return the value. Object methods are a powerful way to add functionality to objects. They allow you to encapsulate code and make it reusable. Syntax Follow the syntax below to add a method to the object. const obj = { sum: function () { // Method body } } obj.sum(); In the above syntax, ”sum” is a method defined inside the ”obj” object. You can access the method as you access the object property and add the pair of parenthesis to invoke the method. Example We added the getInfo() method in the ”company” object in the example below. The getInfo() method returns the string containing the object properties. Here, we used the ”this” keyword to access the object properties inside the object. The ”this” keyword represents the object itself. After that, we used the object as a reference to invoke the method. <html> <body> <p>Company Information</p> <p id = “output”> </p> <script> const company = { companyName: “Tutorials Point”, companyWebsite: “www.tutorialspoint.com”, getInfo: function () { return “Comapny Name: ” + this.companyName +”<br>Website: ” + this.companyWebsite; }, } document.getElementById(“output”).innerHTML = company.getInfo(); </script> </body> </html> Output Company Information Comapny Name: Tutorials Point Website: www.tutorialspoint.com Object Method Shorthand The ES6 provides the shortest way to define a method into the object. Syntax Follow the syntax below to add a method to the object. const Obj = { sum() { // Method body } } Obj.sum(); Like the previous one, you can access and invoke the method in the above syntax. Example In the example below, we defined the getInfo() method as the previous example. <html> <body> <p id = “output”> </p> <script> const employee = { name: “John Doe”, age: 32, getInfo() { return “The employee name is ” + this.name + ” and his age is ” + this.age + ” Years.”; }, } document.getElementById(“output”).innerHTML = employee.getInfo(); </script> </body> </html> Output The employee name is John Doe and his age is 32 Years. Example The example below defines the getSum() method inside the ”nums” object. The getSum() method takes the two parameters and returns their sum. We passed the number arguments to the method while invoking it. <html> <body> <p id = “output”>The sum of 2 and 3 is </p> <script> const nums = { getSum(a, b) { return a + b; } } document.getElementById(“output”).innerHTML += nums.getSum(2, 3); </script> </body> </html> Output The sum of 2 and 3 is 5 Updating or Adding a Method to the Object In JavaScript, updating or adding a new method to the object is same as updating or adding new proeprties to the object. You can either use the dot or square bracket notation to update or add method to the object. Example The example below defines the getSum() method inside the ”nums” object. After that, we add the getMul() method inside the nums object. We invoke the getMul() method by passing two arguments to get the multiplication of them. <html> <body> <p id = “output”>The multiplication of 2 and 3 is </p> <script> const nums = { getSum(a, b) { return a + b; } } nums.getMul = function (a, b) { return a * b; } document.getElementById(“output”).innerHTML += nums.getMul(2, 3); </script> </body> </html> Output The multiplication of 2 and 3 is 6 Using Built-in Methods JavaScript objects like string, number, boolean, etc., also contain built-in methods. You can execute them by taking the object as a reference. Example In the example below, we have defined the ”num” variable containing the numeric value. After that, we used the toString() method to convert the number to a string. <html> <body> <p id = “demo”> </p> <script> const output = document.getElementById(“demo”); const num = new Number(20); let str = num.toString(); output.innerHTML += “After converting the number to string: ” + str + “<br>”; output.innerHTML += “Data type of after conversion: ” + typeof str; </script> </body> </html> Output After converting the number to string: 20 Data type of after conversion: string Print Page Previous Next Advertisements ”;
Category: javascript
ECMAScript 2016
JavaScript – ECMAScript 2016 ”; Previous Next The ECMAScript 2016 version of JavaScript was released in 2016. Previously the old versions of JavaScript are named by numbers for example ES5 and ES6. Since 2016 the versions are named by the year they are released for example ECMAScript 2016, ECMAScript 17, etc. Lets discuss the featues added in ECMAScript 2016. New Features Added in ECMAScript 2016 Here are the new methods, features, etc., added to the ECMAScript 2016 version of JavaScript. Array includes() method Exponentiation Operator (**) Exponentiation Assignment Operator (**=) Here, we have explained each feature in detail. JavaScript Array includes() Method The JavaScript array includes() methods is used to check whether the array contains a particular element. Syntax The syntax of Array includes() method in JavaScript is as follows − arr.include(searchElement, fromIndex); Here arr is the original array, the searchElement is to be search from. The fromIndex is an optional argument if passed, the searching will start from the fromIndex index. Example In the below code, we use the array includes() method to check whether the watches array contains the ”Noise” brand. <html> <body> <div id = “output”>Does watches array include Noise?</div> <script> const watches = [“Titan”, “Rolex”, “Noise”, “Fastrack”, “Casio”]; document.getElementById(“output”).innerHTML += watches.includes(“Noise”); </script> </body> </html> Output Does watches array include Noise? true Example In the below code, we use the array includes() method to check whether the subjects array contains the ”Python” subject searching from index 1. <html> <body> <div id = “output”>Does subjects array include Python fromIndex 1? </div> <script> const subjects = [“Java”, “JavaScript”, “Python”, “C”, “C++”]; document.getElementById(“output”).innerHTML += subjects.includes(“Python”, 1); </script> </body> </html> Output Does subjects array include Python fromIndex 1? true JavaScript Exponentiation Operator The JavaScript exponentiation operator is used to find the power of the first operand raised to the second operand. Syntax The syntax of expponentiation operator is as follow − x ** y; It returns the result of raising the first operand (x) to the power of the second operand (y). Example In the below code, we find the 22 using the exponentiation operator and store the resultant value in the ”res” variable. <html> <body> <div id = “output”>The resultant value for 2 ** 2 is: </div> <script> document.getElementById(“output”).innerHTML += 2 ** 2; </script> </body> </html> Output The resultant value for 2 ** 2 is: 4 Exponentiation Assignment Operator The JavaScript exponentiation assignment operator raises the power of the first operand by the second operand and assigns it to the first operand. Syntax The syntax of exponentiation assignment operator is as follows − x **= y; It assigns the result of raising the first operand (x) to the power of the second operand (y) to x. Example In the below code, we find the 102 and assign the resultant value to the ”num” variable using the exponentiation assignment operator. <html> <body> <div id = “output”>The resultant value for 10 ** 2 is: </div> <script> let num = 10; num **= 2; // exponentiation assignment operation document.getElementById(“output”).innerHTML += num; </script> </body> </html> Output The resultant value for 10 ** 2 is: 100 ECMAScript 2016 Browser Support Most modern browsers support the ECMAScript 2016 version of JavaScript Chrome Firefox Microsoft Edge Opera Safari Firefox Android Yes Yes Yes Yes Yes Yes Print Page Previous Next Advertisements ”;
JavaScript – Object Constructors ”; Previous Next Object Constructors An object constructor in JavaScript is a function that creates an instance of a class, which is typically called an object. A constructor is called when you declare an object using the new keyword. The purpose of a constructor is to create an object and set values if there are any object properties present. There are two ways to create a template for the object in JavaScript – using a class and using an object constructor. Whenever you need to create multiple objects with the same syntax, you require a template for the object. For example, you are managing the car inventory. So, it is not a good idea to create a new object every time using the object literal. In such cases, you need to use the object constructors. The main benefit of the object constructors is that you can reuse the code. Syntax You can follow the syntax below to use the object constructor to create an object. function Funcname(p1, p2, … , pN) { this.prop1 = p1; } const obj = new Funcname(args); In the above syntax, Funcname() is a constructor function, and you can replace any valid identifier with the Funcname. A p1, p2, …, and pN are parameters you can use inside the function body. You need to pass arguments to the constructor while creating the object. The ”this” keyword represents the function context you are using. Here, the ”this” keyword refers to the current instance of the object. To create an object, you can use the function constructor with a ”new” keyword. Example: Creating an object using a constructor function In the example below, we have created a Tree() function. In the function body, we initialize the name and age properties. After that, we use the function name with a ”new” keyword to create an object of the Tree() constructor. <html> <body> <p id = “output”> </p> <script> function Tree() { this.name = “palm”; this.age = 5; } const tree1 = new Tree(); document.getElementById(“output”).innerHTML = “name = ” + tree1.name + “, age = ” + tree1.age; </script> </body> </html> Output name = palm, age = 5 Example: Constructor function with parameters In the example below, the Bike() function takes three parameters. In the function body, we initialize the properties using the parameters. After that, we created bike1 and bike2 objects with different values using the Bike() constructor. In the output, you can observe the object property values. <html> <body> <p id = “output1”>The bike1 object is : </p> <p id = “output2”>The bike2 object is : </p> <script> function Bike(name, speed, gear) { this.name = name; this.speed = speed; this.gear = gear; } const bike1 = new Bike(“Honda”, 100, 4); const bike2 = new Bike(“Yamaha”, 200, 6); document.getElementById(“output1”).innerHTML += JSON.stringify(bike1); document.getElementById(“output2”).innerHTML += JSON.stringify(bike2); </script> </body> </html> Output The bike1 object is : {“name”:”Honda”,”speed”:100,”gear”:4} The bike2 object is : {“name”:”Yamaha”,”speed”:200,”gear”:6} In this way, you can use the object constructor to reuse the object syntax code and create multiple objects of the same type. Adding a Property or Method to a Constructor You learned to add a property of method using the dot or square bracket notation into the object in the Objects chapter. But what if you want to add a property or method to the object constructor? The object constructor doesn”t allow you to add the property or method after defining it. So, you always need to add the required properties and methods while defining it. Let”s understand it via the example below. Example The below example demonstrates adding methods and properties into the object constructor. We added the three properties and the getFullAddress() method in the houseAddress() constructor function. Also, we have executed the method by taking the object as a reference. <html> <body> <p id = “output1”>The house object is </p> <p id = “output2”>The full address of the house is </p> <script> function HouseAddress(no, street, city) { // Adding properties this.houseNo = no, this.street = street, this.city = city; // Adding a method this.getFullAddress = function () { return this.houseNo + “, ” + this.street + “, ” + this.city; }; } const house = new HouseAddress(20, “Cooper Square”, “New York”); document.getElementById(“output1”).innerHTML += JSON.stringify(house); document.getElementById(“output2”).innerHTML += house.getFullAddress(); </script> </body> </html> Output The house object is {“houseNo”:20,”street”:”Cooper Square”,”city”:”New York”} The full address of the house is 20, Cooper Square, New York If you add the method or property as shown below. It will be added to the particular object but not to the constructor function. Obj.prop = 20; Other objects created using the object constructor don”t contain the prop property as it is added to the obj object only. JavaScript Object Prototype In JavaScript, each object contains the prototype property by default, and the object constructor is also one kind of object. So, you can add properties or methods to the object prototype. Syntax You can follow the syntax below to add properties or methods to the object constructor prototype. obj.prototype.name = value; In the above syntax, ”obj” is an object constructor in which you need to add a property or method. The ”name” is a property or method name. For the property, you can replace a ”value” with an actual value; for the method, you can replace a ”value” with a function expression. Example In the example below, we have added the BikeDetails() method to the prototype of the Bike() constructor. The BikDetails() method can be executed using any object of the Bike() constructor. However, when you print the bike1 and bike2 objects, it won”t show you BikeDetails() method as it is added in the prototype. <html> <body> <p id = “output1”>The bike1 details is: </p> <p id = “output2”>The bike2 details is: </p> <script> function Bike(name, speed, gear) { this.name = name; this.speed = speed; this.gear = gear; } Bike.prototype.BikeDetails = function () { return this.name + “, ” + this.speed + “, ” + this.gear + “<br>”; }; const bike1 = new Bike(“Honda”, 100, 4);
JavaScript – Reflect
JavaScript – The Reflect Object ”; Previous Next JavaScript Reflect In JavaScript, Reflect is a global object and was introduced in ECMAScript 6 (ES6). It contains static methods, providing a better way to interact with the object at runtime. Unlike most global objects, Reflect is not a constructor. You cannot use it with the new operator or invoke the Reflect object as a function. All methods of Reflect are static just like the Math object. It contains various methods to access, update, delete, etc. properties from the object at run time. Key Features of the Reflect Object Object construction − The Reflect API allows to create objects at run time using the Reflect.construct() method. Function invocation − The apply() method of the Reflect API is used to invoke a function or object method by passing the context and argument. Object property manipulation − A Reflect API has different methods to set, update, or delete the object properties. Also, it can handle the extension of the object by preventing it. Syntax Following is the syntax to use the method of the Reflect API − Reflect.method(); In the above syntax, the ”method” is the generalization. It can be any method of the Reflect API, such as get, set, apply, construct, has, etc. Reflect Methods In the following table, we have listed all the methods of Reflect − Sr.No. Name & Description 1 apply() To invoke a function. 2 construct() Allows to specify the different prototypes. 3 defineProperty() Allows to insert or edit object property. 4 deleteProperty() Allows to delete the object property. 5 get() To get a value of the property. 6 getOwnPropertyDescriptor() Allows to get the descriptor of the object. 7 getPrototypeOf() To get the prototype of the object. 8 has() To check whether the property exists in the object. 9 isExtensible() Allows to check whether the object is extensible. 10 ownKeys() Returns the own keys of the targeted object and ignores the inherited keys. 11 preventExtensions() To prevent the extension of the object. 12 set() To set the value to the object property. 13 setPrototypeOf() Allows to set the prototype of the object as null or another object. Examples Example 1 In the example below, we have defined a car object. The ”prop” variable contains the property name in the string format. We use the get() method of the Reflect object to access the ”model” property from the car object. We passed the object name as a first parameter of the get() method and the property name as a second parameter. In the output, you can see the value of the ”model” property. <html> <body> <div id=”output”>The model of the car is: </div> <script> const car = { name: “Audi”, model: “Q6”, price: 7000000, } let prop = “model”; let model = Reflect.get(car, prop); document.getElementById(“output”).innerHTML += model; </script> </body> </html> Output The model of the car is: Q6 Example 2 In the example below, we used the set() method to set the property into the object. The set() method takes an object, property name, and value as a parameter. The output shows the ”doors” property value. In this way, you can set the property into the object at run time using the set() method of the Reflect API. <html> <body> <div id=”output”>The total doors in the Audi Q6 is: </div> <script> const car = { name: “Audi”, model: “Q6”, price: 7000000, } const model = Reflect.set(car, “doors”, 4); document.getElementById(“output”).innerHTML += car.doors; </script> </body> </html> Output The total doors in the Audi Q6 is: 4 On executing the above script, the output window will pop up, displaying the text on the webpage. Example 3 In the example below, we used the has() method to check whether the particular property exists in the object dynamically. Both symbols look similar but are different, which you can see in the output. <html> <body> <p id=”output”></p> <script> const car = { name: “Audi”, model: “Q6”, price: 7000000, } const isName = Reflect.has(car, “name”); if (isName) { document.getElementById(“output”).innerHTML = “The Car object contains the name.”; } </script> </body> </html> Output The Car object contains the name. Print Page Previous Next Advertisements ”;
JavaScript – Symbol
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
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 – 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 – Abstraction
JavaScript – Abstraction ”; Previous Next Abstraction in JavaScript The Abstraction in JavaScript can be achieved using the abstract class. In object-oriented programming, the abstraction concept allows you to hide the implementation details and expose features only to the users. For example, you can execute the Math object methods in JavaScript by accessing the method using its name but can’t see how it is implemented. Same way array methods like push(), pop(), etc., can be executed, but you don’t know how it is implemented internally. So, the abstraction makes code cleaner by exposing the required features and hiding the internal implementation details. How to Achieve Abstraction in JavaScript? In most programming languages, you can achieve abstraction using the abstract class. The abstract class contains only method declaration but not implementation. Furthermore, you need to implement the methods declared in the abstract class into the child class. Also, you can’t create an instance of the abstract class. JavaScript doesn’t allow to create an abstract class like Java or CPP natively, but you can achieve the same functionality using the object constructor function. First, let’s create an abstract class using the example below. Creating the Abstract Class In the below example, the fruit() function initializes the name property. When anyone creates an instance of the fruit(), the value of the constructor property becomes equal to the ‘fruit’. So, we throw an error to prevent creating an instance of the fruit. Also, we have added the getName() method to the prototype. After that, we create an instance of the fruit() constructor, and you can observe the error in the output. <html> <body> <div id = “output”> </div> <script> try { // Object constructor function fruit() { this.name = “Fruit”; if (this.constructor === fruit) {// Preventing the instance of the object throw new Error(“You can”t create the instance of the fruit.”); } } // Implementing method in the prototype fruit.prototype.getName = function () { return this.name; } const apple = new fruit(); } catch (error) { document.getElementById(“output”).innerHTML = error; } </script> </body> </html> Output Error: You can”t create the instance of the fruit. In the above example, you learned to achieve the abstract class functionality. Now, you will learn to extend the abstract class and implement the methods defined in the abstract class via the example below. Extending the Abstract Class In the example below, fruit() constructor is similar to the above example. We have implemented the Apple() constructor, initializing the name property. After that, we assign the prototype of the fruit() function to the Apple() function using the Object.create() method. It means Apple() function inherits the properties and methods of the fruit() class. After that, we have created the instance of the Apple() class and invoked the getName() method. <html> <body> <div id = “output”>The name of the fruit is: </div> <script> // Abstract class function fruit() { this.name = “Fruit”; if (this.constructor === fruit) { // Preventing the instance of the object throw new Error(“You can”t create the instance of the fruit.”); } } // Implementing method in the prototype fruit.prototype.getName = function () { return this.name; } // Child class function Apple(fruitname) { this.name = fruitname; } // Extending the Apple class with the fruit class Apple.prototype = Object.create(fruit.prototype); const apple = new Apple(“Apple”); document.getElementById(“output”).innerHTML += apple.getName(); </script> </body> </html> Output The name of the fruit is: Apple The prototype implements the getName() method in the above code. So, it is hidden. This way, you can use an object constructor to achieve abstraction in JavaScript. Print Page Previous Next Advertisements ”;
JavaScript – Sets
JavaScript – Sets ”; Previous Next A JavaScript Set object is a collection of unique values. Each value can only occur once in a Set. A Set can hold any value of any data type. The sets are introduced to JavaScript in ECMAScript 6 (ES6). JavaScript Sets are similar to Arrays, but there are some key differences: Sets can only hold unique values, while Arrays can hold duplicate values. Sets are not ordered, while Arrays are ordered. Sets are faster to add and remove items from than Arrays. JavaScript Sets are often used to store unique values, such as the unique users who have visited a website. They can also be used to remove duplicate values from an Array. Syntax Users can follow the syntax below to define a set in JavaScript − let set1 = new Set([iterable]); In the above syntax, we used the Set() constructor function with a ‘new’ keyword to define a set. Parameters Iterable− It is an optional parameter. The Set() constructor function traverses through the elements of the iterable and creates a new set using those elements. Examples Example (Access set elements) In the example below, we have passed the array containing the duplicate elements as an argument of the Set() constructor function. The num_set contains only unique values. We used the values() method to get the iterator of the set values. To traverse the iterator, we use the for…of loop. In the loop, we access the element and print it. You can observe that set contains unique values even if the input array contains duplicate elements. <html> <body> <p>The set elements are: </p> <p id = “output”></p> <script> const num_set = new Set([10, 20, 20, 20]); for (let value of num_set.values()) { document.getElementById(“output”).innerHTML += value + “<br> “; } </script> </body> </html> Output The set elements are: 10 20 Example (Insert elements into the sets) Users can use the add() method to insert the element into the set. Here, we have created the empty set. After that, we used the add() method 3 times to add the 60, 50, 50 elements into the set. We inserted the 50 for 2 times, but the set contains only once as it contains unique values. <html> <body> <p>Set elements after adding element/s to it: </p> <div id = “output”> </div> <script> const num_set = new Set(); num_set.add(60); num_set.add(50); num_set.add(50); for (let value of num_set.values()) { document.getElementById(“output”).innerHTML += value + “<br> “; } </script> </body> </html> Output Set elements after adding element/s to it: 60 50 Example (Remove set elements) The delete() method of the set allows you to delete the element from the set. Here, we created the set containing the various numbers and used the delete() method to delete the 200 and 400 from the set. <html> <body> <p> After deleting elements from the set: </p> <div id = “output”> </div> <script> let num_set = new Set([100, 200, 300, 400, 500]); num_set.delete(200); num_set.delete(400); for (let value of num_set.values()) { document.getElementById(“output”).innerHTML += value + “<br> “; } </script> </body> </html> Output The set contains 100?: true Example (Check if the set contains a specific value) The example below demonstrates of using the has() method to check whether the set contains the specific value. Here, we check whether the set contains 100 and print the message in the output accordingly. <html> <body> <p id = “output”>The set contains 100?: </p> <script> const num_set = new Set([100, 200, 300, 400, 500]); document.getElementById(“output”).innerHTML += num_set.has(100); </script> </body> </html> Output It returns “true” because the element 100 is present in the set. The set contains 100?: true Mathematical set operations The Set class doesn’t contain the built-in methods to perform the mathematical set operations like union, intersection, or set difference. So, you need to write the custom JavaScript code to perform the mathematical operations as shown below. Example (Union of two sets) The union of two sets contains all unique elements of set1 and set2. In the example below, set1 and set2 contain the car names. We have defined the ‘union’ set and passed the array as an argument. We used the spread operator to create an array containing the elements of set1 and set2. <html> <body> <p>The Union of set1 and set2 is: </p> <div id = “output”> </div> <script> const set1 = new Set([“BMW”, “Audi”, “TATA”]); const set2 = new Set([“BMW”, “TaTa”, “Honda”, “Suzuki”]); const union = new Set([…set1, …set2]); // Taking union for (let value of union.values()) { document.getElementById(“output”).innerHTML += value + “<br> “; } </script> </body> </html> Output If we execute the program, it returns all unique elements of set1 and set2. The Union of set1 and set2 is: BMW Audi TATA TaTa Honda Suzuki Example (Intersection of two sets) The intersection of two sets contains the unique elements which exist in set1 and set2 both. Here, we have two sets containing the car names and defined the ‘inter’ set to store the set elements which exist in both sets. We traverse through the elements of set1, and inside the loop we use the has() method to check whether the element of the set1 exists in the set2. If yes, we add an element into the ‘inter’ set. <html> <body> <p> The intersection of set1 and set2 is: </p> <p id = “output”> </p> <script> const set1 = new Set([“BMW”, “Audi”, “TATA”]); const set2 = new Set([“BMW”, “TATA”, “Honda”, “Suzuki”]); const inter = new Set(); for (let car of set1) { if (set2.has(car)) { inter.add(car); } }