Author: Saim Khalid

  • Display Objects

    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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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 +" &lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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]+" &lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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.

  • Static Methods

    What are Static Methods?

    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 −

    classTable{staticgetSize(){// Static methodreturn"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");classTable{staticprintSize(){return"The size of the table is: 20 x 20 <br>";}getColor(){return"Black";}}
    
    		output.innerHTML = Table.printSize();// Static method executionconst tableObj =newTable();
    		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>classTable{staticprintSize(){return"The size of the table is 20 x 20 <br>";}staticgetColor(){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>classTable{staticprintSize(){return"The size of the table is: 20 x 20 <br>";}staticprintSize(){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>classNum{constructor(a){// Static method executionthis.sqrt =this.constructor.getSqrt(a);}staticgetSqrt(a){return a * a;}}const num1 =newNum(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");classNum{staticgetSqr(a){return a * a;}printSqr(a){
    
    			output.innerHTML +="The square of "+ a +" is: "+ Num.getSqr(a)+"&lt;br&gt;";}}const num1 =newNum();
    num1.printSqr(6);</script></body></html>

    Output

    The square of 6 is: 36
  • Object Methods

    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 of2 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 of2 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 =newNumber(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

  • Object Properties

    JavaScript Object Properties

    An object property in JavaScript is a key: value pair, where key is a string and value can be anything. The key in key: value pair is also called property name. So the properties are association between key (or name) and value.

    An object is in other terms a collection of properties (key: value pairs). However, key: value pairs are not stored in the specific order in the object. To write an object syntax, the curly braces are used. Each key: value pair is written within curly braces separated by a comma.

    You can manipulate the object properties in JavaScript. For example, you can add, delete, or update the object’s properties.

    Syntax

    You can follow the syntax below to define properties in the object.

    const fruit ={
    
    name:"Apple",
    price:100,}</pre>

    In the above syntax, fruit is an object. The fruit object contains the name and price properties. The value of the name property is 'Apple, and the price is 100.

    In an object, the key can either be a string or a symbol only. If you use another data type as a key, the object implicitly converts it into the string.

    The property value can be anything like an object, set, array, string, set, function, etc.

    Accessing Object Properties

    There are 3 ways to access object properties in JavaScript.

    • Using the dot notation
    • Using the square bracket notation
    • Using the expression

    The Dot Notation

    You can access the object property using the dot notation/ syntax.

    obj.prop;

    In the above syntax, 'obj' is an object, and 'prop' is its property whose value you need to access.

    Example

    The 'fruit' object in the example below contains the name and price property. We access the object properties using the dot notation, and you can see property values in the output.

    <!DOCTYPE html><html><body><p id ="output"></p><script>const fruit ={
    			name:"Banana",
    			price:20,}
    		document.getElementById("output").innerHTML ="The price of the "+ fruit.name +" is "+ fruit.price;</script></body></html>

    Output

    The price of the Banana is 20
    

    The Square Bracket Notation

    You can use the square bracket pair containing the property as a string followed by the object name to access a particular property.

    obj["prop"]

    In the above syntax, we access the 'prop' property from the object.

    You can't access the property using the dot notation when you use invalid identifiers as an object key. So, you need to use the square bracket notation. The identifier is invalid if it starts from a number, contains a space, or a hyphen.

    Example

    In the example below, we access the fruit object's name and price property values.

    <!DOCTYPE html><html><body><p id ="output"></p><script>const fruit ={
    			name:"Banana",
    			price:20,}
    		document.getElementById("output").innerHTML ="The price of the "+ fruit["name"]+" is "+ fruit["price"];</script></body></html>

    Output

    The price of the Banana is 20
    

    Using the expression inside the bracket

    Sometimes, you require to access the object properties dynamically using the variable or expression. So, you can write the expression inside the square bracket notation. The expression can be a variable, a mathematical expression, etc.

    obj[expression]

    The above syntax evaluates the expression first and accesses the property same as a resultant value from the object. You don't need to write the expression in quotes.

    Example

    In the example below, the num object contains the number as a key in the string format and its word representation as a value.

    We use the variable x to access the property value from the object. Also, we used the "x + 10" mathematical expression to access the object property dynamically.

    <!DOCTYPE html><html><body><p id ="output"></p><script>const num ={10:"ten",20:"Twenty",}const x =10;
    		document.getElementById("output").innerHTML =  num[x +10];</script></body></html>

    Output

    Twenty
    

    Accessing the Nested Object Properties

    Accessing the nested object properties is very similar to accessing the object properties. You can either use the dot or square bracket notation.

    Syntax

    Obj.prop.nestedProp
    // OR
    Obj["prop"]["nestedProp"];

    In the above syntax, the prop is a property of the obj object, and nestedProp is a property of the 'prop' object.

    Example

    In the below code, the 'cars' object contains the nested objects named OD and BMW. We access the nested object properties using the dot and square bracket notation.

    <!DOCTYPE html><html><body><p id ="output1"></p><p id ="output2"></p><script>const cars ={
    			totalBrands:50,
    			audi:{
    
    			model:"Q7",
    			price:10000000,},
    bmw:{
    			model:"S20D",
    			price:8000000,}}
    document.getElementById("output1").innerHTML ="The model of Audi is "+ cars.audi.model +" and its price is "+ cars.audi.price; document.getElementById("output2").innerHTML ="The model of BMW is "+ cars["bmw"]["model"]+" and its price is "+ cars["bmw"]["price"];</script></body></html>

    Output

    The model of Audi is Q7 and its price is 10000000
    
    The model of BMW is S20D and its price is 8000000
    

    Adding or Updating the Object Properties

    You can update or add new properties to the object using the dot or square bracket notation. You can access the object property and assign a new value to it. If the property already exists, it updates the property value. Otherwise, it adds the property to the object.

    Syntax

    Obj.prop = new_value;OR
    Obj["prop"]= new_value;

    In the above syntax, we update the value of the 'prop' property of the obj object.

    Example

    In the example below, we update the name and price property of the fruit object. Also, we add the expiry property to the fruit object.

    <!DOCTYPE html><html><body><p id ="output"></p><script>const fruit ={
    			name:"Watermealon",
    			price:150,}
    		fruit.name ="Apple";// Updating using the dot notation
    		fruit["price"]=200;// Updating using the bracket notation
    		fruit.expiry ="5 days";// Adding new property to the object.
    
    		document.getElementById("output").innerHTML +="The price of "+ fruit.name +" is "+ fruit.price +" and it expires in "+ fruit.expiry;</script></body></html>

    Output

    The price of Apple is 200 and it expires in 5 days
    

    Deleting the Object Properties

    You can use the 'delete' operator to delete the specific object properties.

    Syntax

    delete obj.prop;

    In the above syntax, obj.prop is an operator for the delete operator.

    Example

    In the example below, we delete the name property from the fruit object using the delete operator. The output shows that the fruit object contains only the price property after deleting the name property.

    <!DOCTYPE html><html><body><p> The object after deleting the "name" property:</p><p id ="output"></p><script>const fruit ={
    			name:"Watermealon",
    			price:150,}delete fruit.name;
    		document.getElementById("output").innerHTML =JSON.stringify(fruit);</script></body></html>

    Output

    The object after deleting the "name" property:
    
    {"price":150}
    

    Enumerating the Object Properties

    There are various approaches to enumerating the object properties. The Object.keys() method returns the object's keys in the array. However, we will use the forin loop to traverse through each property of the object.

    Syntax

    You can follow the syntax below to iterate through the object properties.

    for(let key in table){// Use the key to access its value}

    In the above syntax, 'key' is an object property, which can be used to access its value.

    Example

    In the example below, we have created the table object containing 3 properties. After that, we used the forin loop to traverse through each property of the object and access its value.

    <!DOCTYPE html><html><body><p> Iterating the obejct properties</p><p id ="output"></p><script>const table ={
    			color:"brown",
    			shape:"round",
    			price:10000,}for(let key in table){
    			document.getElementById("output").innerHTML += key +": "+ table[key]+"<br>";}</script></body></html>

    Output

    Iterating the obejct properties
    
    color: brown
    shape: round
    price: 10000
    

    Property Attributes

    The object property contains four attributes.

    • value − A value of the object.
    • enumerable − Contains boolean value representing whether the object is iterable.
    • configurable − Contains the boolean value representing whether the object is configurable.
    • writable − It also contains the boolean value, representing whether the object is writable.

    By default, you can't edit other attributes except the value attribute of the object property. You need to use the defineProperty() or defineProperties() methods to update other attributes.

  • Classes

    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.

    functionCar(brand){// Constructor functionthis.brand = brand;// property initialization}const carObj =newCar("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 declarationclassClassName{// Class body}//Class expressionconst 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 classis:</p><script>classCar{// 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 −

    classCar{constructor(brand){// Defining the constructorthis.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 =newCar("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 classclassCar{constructor(){this.brand ="BMW";this.model ="X5";this.year =2019;}}// instantiate myCar objectconst myCar =newCar();// 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>classCar{constructor(brand, model, price, year){this.brand = brand;this.model = model;this.price = price;this.year = year;}}const carObj =newCar("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.

    classcar{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><body><p id ="output"></p><script>classCar{constructor(brand, model, price, year){this.brand = brand;this.model = model;this.price = price;this.year = year;}updateprice(newPrice){this.price = newPrice;}}const myCar =newCar("BMW","X5",9800000,2019);
    		document.getElementById("output").innerHTML +="The car price is : "+ myCar.price +"<br>";
    
    myCar.updateprice(8800000);// updating price
    document.getElementById("output").innerHTML +="After updating the car price is : "+ myCar.price +"<br>";</script></body></html>

    Output

    The car price is : 9800000
    After updating the car price is : 8800000
    

    JavaScript Class Hoisting

    In JavaScript, the declaration of the class is not hoisted at the top of the code. So, you always need to define the class before you use it.

    const carObj =newCar();// This will generate an error.classCar{}

    You can try to run the above code. It will generate a reference error as the car class is used before its initialization.

    Strict Mode with Classes

    The strict mode is used to avoid unusual errors. The class code is always in the strict mode by default.

    Let’s understand it via the example below.

    classnumbers{constructor(){
    		num =90;// Defining variable without var keyword}}const numObj =newnumbers();

    In the above code, we define the ‘num’ global variable in the constructor() method. In the strict mode of JavaScript, it is not allowed to define the variables without using the var, let, or const keywords. So, the above code will throw an error.

  • Objects Overview

    JavaScript Objects

    The JavaScript object is a non-primitive data type that is used to store data as key-value pairs. The key-value pairs are often referred as properties. A key in a key-value pair, also called a “property name”, is a string and value can be anything. If a property’s value is a function, the property is known as a method.

    Objects are created using curly braces and each property is separated by a comma. Each property is written as property name followed by colon (:) followed by property value. The key: value pairs are not stored in the specific order in the object. So an object is an unordered collection of properties written as key: value pairs.

    JavaScript is an Object Oriented Programming (OOP) language. A programming language can be called object-oriented if it provides four basic capabilities to developers.

    • Encapsulation − the capability to store related information, whether data or methods, together in an object.
    • Abstraction − the capability to hide object’s implementation details from users.
    • Inheritance − the capability of a class to rely upon another class (or number of classes) for some of its properties and methods.
    • Polymorphism − the capability to write one function or method that works in a variety of different ways.

    Let’s understand in details about the JavaScript objects.

    Object Properties

    Object properties can be any of the primitive data types, objects or functions. Object properties are usually variables that are used internally in the object’s methods, but can also be globally visible variables that are used throughout the page.

    The syntax for adding a property to an object is −

    objectName.objectProperty = propertyValue;

    For example − The following code gets the document title using the “title” property of the document object.

    var str = document.title;

    Object Methods

    Methods are the functions that let the object do something or let something be done to it. There is a small difference between a function and a method at a function is a standalone unit of statements and a method is attached to an object and can be referenced by the this keyword.

    Methods are useful for everything from displaying the contents of the object to the screen to performing complex mathematical operations on a group of local properties and parameters.

    For example − Following is a simple example to show how to use the write() method of document object to write any content on the document.

    document.write("This is test");

    Creating New Objects

    All user-defined objects and built-in objects are descendants of an object called Object.

    We can use object literals to create a new user-defined object. Alternatively, we can create a constructor function and then invoke this function using new keyword to instantiate an object.

    There are different ways to create an object in JavaScript. Here, we will learn all ways given below.

    • Using the Object Literal
    • Using the Object Constructor
    • Using the Object.create() Method
    • Using JavaScript ES6 Classes

    The JavaScript Object Literal

    In JavaScript, {} is represented by the object literal. You can add pair of key-value pairs between curly braces to define an object.

    You can follow the syntax below to use the object literal to define objects.

    const obj ={
       key: val,}

    You can add key-value pairs between curly braces. Each key-value pair is comma separated, and you need to add a colon (:) between the key and value.

    Example

    In the example below, we have defined a wall object containing the 4 properties. Each property contains the different values of different data types.

    In the output, you can observe the object properties and its value.

    <html><body><p id ="output"></p><script>const myBook ={
    
         title:"Perl",
         author:"Mohtashim",
         pages:355,}
      document.getElementById("output").innerHTML ="Book name is : "+ myBook.title +"&lt;br&gt;"+"Book author is : "+ myBook.author +"&lt;br&gt;"+"Total pages : "+ myBook.pages;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Book name is : Perl
    Book author is : Mohtashim
    Total pages : 355
    

    The JavaScript new Operator

    The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method.

    In the following example, the constructor methods are Object(), Array(), and Date(). These constructors are built-in JavaScript functions.

    var employee =newObject();var books =newArray("C++","Perl","Java");var day =newDate("August 15, 1947");

    The JavaScript Object() Constructor

    A constructor is a function that creates and initializes an object. JavaScript provides a special constructor function called Object() to build the object. The return value of the Object() constructor is assigned to a variable.

    The variable contains a reference to the new object. The properties assigned to the object are not variables and are not defined with the var keyword.

    Example

    Try the following example; it demonstrates how to create an Object.

    <html><body><p id ="output"></p><script>var book =newObject();// Create the object
    
      book.subject ="Perl";// Assign properties to the object
      book.author  ="Mohtashim";
      document.getElementById("output").innerHTML ="Book name is : "+ book.subject +"&lt;br&gt;"+"Book author is : "+ book.author;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Book name is : Perl
    Book author is : Mohtashim
    

    The JavaScript Constructor Function

    In JavaScript, you can define a custom function and use it as a constructor function to define a new object. Here, the custom function works as a template.

    The benefit of the custom user-defined constructor function over the Object() constructor is that you can add arguments to the custom function according to your requirements.

    Below is simple syntax to use the custom user-defined constructor function to create an object.

    // Object templatefunctionConstructorFunc(para){this.para = para;}const obj =newConstructorFunc(arg);

    The ConstructorFunc() function works as an object template. It uses the 'this' keyword to access the context of the function and define the key in the function context. Also, the key is initialized with the 'para' value.

    Next, you can use the function as a constructor with a 'new' keyword to define the object and pass the required arguments to the constructor.

    Example

    This example demonstrates how to create an object with a user-defined constructor Function. Here this keyword is used to refer to the object that has been passed to a function.

    <html><body><div id ="output"></div><script>functionBook(title, author){this.title = title;this.author  = author;}const myBook =newBook("Perl","Mohtashim");
    
      document.getElementById("output").innerHTML ="Book title is : "+ myBook.title +"&lt;br&gt;"+"Book author is : "+ myBook.author +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Book title is : Perl
    Book author is : Mohtashim
    

    The JavaScript Object.create() Method

    The Object.create() method creates a new object from the already defined object. Also, you can add some new properties to the object prototype while cloning one object from another object using the Object.create() method.

    Follow the syntax below to use the Object.create() method to define a new object.

    const obj = Object.create({},{
    
    key:{ value: val },})</pre>
    • {} − It is an empty object. The Object.create() method creates a copy of it.
    • { key: { value: val }, } − It is an object containing the properties to add to the prototype of the cloned object.

    Example

    In the example below, we added multiple properties to the prototype of the empty object. However, if you print the object, you won't be able to see any properties as they are added to the prototype.

    You can access the object properties with a dot notation.

    <html><body><p id ="output"></p><script>const myBook = Object.create({},{
    
         title:{ value:"Perl"},
         author:{ value:"Mohtashim"},})
        
      document.getElementById("output").innerHTML ="Book title is : "+ myBook.title +"&lt;br&gt;"+"Book author is : "+ myBook.author +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Book title is : Perl
    Book author is : Mohtashim
    

    The JavaScript ES6 Classes

    The JavaScript classes are introduced in ES6. The JavaScript classes are template to create objects. A class is defined using the "class" keyword. It is similar to the function while defining a class. The class keyword is followed by the class name and then class body.

    classMyClass{//class body}

    You can use the new operator to create an object using a class −

    const myObj =newMyClass();

    Here ClassName is the name of class and myObject is the name of object creating using this class.

    We have discussed the JavaScript classes in details in the next chapter.

    Defining Methods for an Object

    The previous examples demonstrate how the constructor creates the object and assigns properties. But we need to complete the definition of an object by assigning methods to it.

    Example

    Try the following example; it shows how to add a function along with an object.

    <html><head><title>User-defined objects</title><script>// Define a function which will work as a methodfunctionaddPrice(amount){this.price = amount;}functionBook(title, author){this.title = title;this.author  = author;this.addPrice = addPrice;// Assign that method as property.}</script></head><body><div id ="output"></div><script>var myBook =newBook("Perl","Mohtashim");
    
      myBook.addPrice(100);
      document.getElementById("output").innerHTML ="Book title is : "+ myBook.title +"&lt;br&gt;"+"Book author is : "+ myBook.author +"&lt;br&gt;"+"Book price is : "+ myBook.price +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Book title is : Perl 
    Book author is : Mohtashim 
    Book price is : 100
    

    The 'with' Keyword

    The with keyword is used as a kind of shorthand for referencing an object's properties or methods.

    The object specified as an argument to with becomes the default object for the duration of the block that follows. The properties and methods for the object can be used without naming the object.

    Syntax

    The syntax for with object is as follows −

    with (object) {
       properties used without the object name and dot
    }
    

    Example

    Try the following example.

    <html><head><script>// Define a function which will work as a methodfunctionaddPrice(amount){with(this){
    
        price = amount;}}functionBook(title, author){this.title = title;this.author = author;this.price =0;this.addPrice = addPrice;// Assign that method as property.}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;div id ="output"&gt;&lt;/div&gt;&lt;script&gt;var myBook =newBook("Perl","Mohtashim");
    myBook.addPrice(100);
         
    document.getElementById("output").innerHTML ="Book title is : "+ myBook.title +"&lt;br&gt;"+"Book author is : "+ myBook.author +"&lt;br&gt;"+"Book price is : "+ myBook.price +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Book title is : Perl 
    Book author is : Mohtashim 
    Book price is : 100
    

    JavaScript Native Objects

    JavaScript has several built-in or native objects. These objects are accessible anywhere in your program and will work the same way in any browser running in any operating system.

    Here is the list of all important JavaScript Native Objects −

    • JavaScript Number Object
    • JavaScript Boolean Object
    • JavaScript String Object
    • JavaScript Array Object
    • JavaScript Date Object
    • JavaScript Math Object
    • JavaScript RegExp Object
    • JavaScript Symbol Object
    • JavaScript Set Object
    • JavaScript WeakSet Object
    • JavaScript Map Object
    • JavaScript WeakMap Object
    • JavaScript Iterables Object
    • JavaScript Reflect Object
    • JavaScript TypedArray Object

    JavaScript Object Methods

    Here, we have listed the methods of JavaScript object.

    Static methods

    These methods are invoked using the Object class itself.

    Sr.No.MethodDescription
    1assign()To copy properties and their values from one object to another object.
    2create()To create a new object using an existing object as prototype.
    3defineProperty()To make a clone of the object and add new properties to its prototype.
    4defineProperties()To define a property into a particular object and get the updated object.
    5entries()It returns an array containing the [key, value] pairs.
    6freeze()To prevent adding or updating object properties by freezing the object.
    7fromEntries()To create a new object from the array of the [key, value] pairs.
    8getOwnPropertyDescriptor()To get the property descriptor for the properties of the object.
    9getOwnPropertyNames()To get object properties.
    10getOwnPropertySymbols()To get all symbols in the array form which are present in the object.
    11getPrototypeOf()To get the prototype of the object.
    12hasOwn()To check whether the particular property exists in the object.
    13Object.is()To check whether the two objects contain a similar value.
    14isExtensible()To check if an object is extensible.
    15isFrozen()To check if the object is frozen.
    16isSealed()To check if the object is sealed.
    17keys()To get all keys of the object in the array format.
    18preventExtensions()To prevent the prototype updation of the object.
    19seal()To seal the object.
    20setPrototypeOf()To set a prototype of the object.
    21toLocaleString()To get the object in the string format.
    22values()To get all values of the object in the array format.

    Instance methods

    These methods are invoked using the instance of the object.

    Sr.No.MethodDescription
    1defineGetter()To define getters to get the particular property value.
    2hasOwnProperty()To check if the object has a particular property as its own property.
    3isPrototypeOf()To check whether the particular object exists as a prototype of the other object.
    4propertyIsEnumerable()To check whether the property of the object is enumerable.

    Object Properties

    Sr.No.PropertyDescription
    1constructorTo get the reference to the constructor function of the object.
  • Tagged Templates

    JavaScript Tagged Templates

    The tagged templates in JavaScript are an advanced version of the template literals. You can define the function to format the string and use it with a template literal to format the string according to the functionality of the function.

    The tagged template can be used with the string using the function name only, and it does not need to add the parenthesis while using the function.

    Syntax

    Following is the syntax to use the tagged templates in JavaScript −

    functionformat(str, exp1, exp2, ...expN){//    Format the string}let res = format${exp1} abcd ${exp2};

    The format() function works as a template tag in the above syntax. The function takes multiple parameters, which you can use inside the function body to format the string.

    Parameters

    • str − It is an array of strings of template literal.
    • exp1, exp2, …expN − They are expressions of the template literals.

    Examples

    Example: Basic Tagged Template

    In the example below, we have defined the format() function. The format() function takes the array of strings as a parameter.

    The function body joins all elements of the str array, converts the string into the upper case using the toUpperCase() method, and returns the updated string.

    In the output, you can see that the template tagged has converted the string into uppercase.

    <html><body><p id ="output"></p><script>functionformat(str){return str.join("").toUpperCase();}let res = formatHi How are you?;
    
      document.getElementById("output").innerHTML = res;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    HI HOW ARE YOU?
    

    Example: Expression with Tagged Templates

    In the example below, the format() function takes the array of strings and name variable as a parameter. We join all string instances in the function body and append the name at the end. After that, return the updated string.

    In the output, you can see the name at the end of the string.

    <html><body><p id ="output"></p><script>functionformat(str, name){return str.join(" ")+ name;}let name ="John";let res = formatHi ${name}, How are you?;
    
      document.getElementById("output").innerHTML = res;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Hi , How are you?John
    

    Example: Using Rest Parameter

    You can also use the spread operator (parameter) to collect all expressions in the single function parameters. Otherwise, you need to pass the parameter for each expression used in the string separately.

    In the below example, we use spread operator to pass two parameters, name and price. In output you can notice the values of the parameters (arguments) are displayed.

    <html><body><div id ="output1"></div><div id ="output2"></div><script>functionformat(str, ...values){
    
         document.getElementById("output1").innerHTML = values;return str.join(" ")+ values[1];}const price =100;let name ="John"const res = formatHi,${name} The price is ${price};
      document.getElementById("output2").innerHTML = res;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    John,100
    Hi, The price is 100

  • Tempate Literals

    JavaScript Tempate Literals

    In JavaScript, the template literals are introduced in ES6 to customize the string dynamically. The template literals allow you to add variables or expressions into the string, and the string changes according to the variables and expression value changes.

    There are multiple synonyms words used for the template literal words. For example, template string, string templates, back-tics syntax, etc.

    Syntax

    Follow the syntax below to use the template literals in JavaScript.

    let str =Hi ${name};

    You need to write a string between back-tics (“). For using the dynamic variable or expression with a string, you need to place it between the ${}.

    Furthermore, using the template literals, you dont need escape characters to add single or double quotes in the string.

    Examples

    Example: Creating Strings with Template Literals

    In the example below, we used the template literals to create a string with special characters.

    The str1 string is the same as the regular string we create using single or double quotes. The str2 string contains the single quotes with the string. Here, you can see that we havent used the escape characters to add a single quote in the string.

    <html><body><div id ="output1"></div><div id ="output2"></div><script>let str1 =Hello Users!;let str2 ='Tutorialspoint' is a good website;
    
      document.getElementById("output1").innerHTML = str1;
      document.getElementById("output2").innerHTML = str2;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Hello Users!
    'Tutorialspoint' is a good website
    

    Example: Variables with Template Literals

    The below code demonstrates to use the dynamic values in the string by passing the variables into the template literal string.

    Here, we have defined the variables related to cars. After that, we create a string using the template literals and add the variables.

    In the output, you can see that variables are replaced with their value in the string.

    <html><body><p id ="output"></p><script>let car ="BMW";let model ="X5";const price =5000000;const carStr =The price of the ${car} ${model} is ${price}.;
    
      document.getElementById("output").innerHTML = carStr;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The price of the BMW X5 is 5000000.
    

    Example: Expressions with Template Literals

    You can also add the expressions to the string using the template literals.

    In the str1 string, we added the expression to perform the summation of two numbers in the template literals string.

    In str2, we invoke the function invocation as an expression. It replaces the expression with a returned value from the function.

    <html><body><div id ="output1"></div><div id ="output2"></div><script>functionfunc(){return10;}const str1 =The sum of 2 and 3 is ${2 + 3}.;const str2 =The return value from the function is ${func()};
    
      
      document.getElementById("output1").innerHTML = str1;
      document.getElementById("output2").innerHTML = str2;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The sum of 2 and 3 is 5.
    The return value from the function is 10
    

    JavaScript Nested Template Literals

    JavaScript allows you to use the template literals inside other template literals, and it is called the nested template literals.

    Example

    In the example below, we added the expression in the outer template literal. The expression contains the ternary operator. It checks whether the 2 is less than 3. Based on the returned boolean value, it executes the first or second nested expression and prints the result.

    <html><head><title>Nested Template Literals</title></head><body><p id ="output"></p><script>const nested =The subtraction result is: ${2 &lt; 3 ? ${3 - 2} : ${2 - 3}};
    
      document.getElementById("output").innerHTML = nested;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The subtraction result is: 1
    

    Example: Multiline String Using Template Literal

    You can also use the template literals to define the multiline string.

    <html><body><div id ="output"></div><script>functionfunc(){return10;}const str1 =`The sum of 2 and 3 is ${2 + 3}. <br>
    
      The return value from the function is ${func()}`;
      
      document.getElementById("output").innerHTML = str1;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The sum of 2 and 3 is 5.
    The return value from the function is 10

  • The TypedArray Object

    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.TypedArrayData TypeRangeExample
    1Int8Array8-bit two’s complement Signed integer (byte)-28 to 127new Int8Array([92, 17, -100])
    2Uint8Array8-bit Unsigned integer0 to 255new Uint8Array([132, 210, 0])
    3Uint8ClampedArray8-bit Unsigned integer0 to 255new Uint8ClampedArray([90, 17, 70])
    4Int16ArrayShort integer-32768 to 32767new Int16Array([1000, -2000, 150])
    5Uint16ArrayUnsigned short int0 to 65535new Uint16Array([50, -6535, 12000])
    6Int32ArraySigned long integer-2147483648 to 2147483647new Int32Array([1000000, -2000000, 9876])
    7Uint32ArrayUnsigned long integer0 to 4294967295new Uint32Array([100, 42967295, 0])
    8Float32ArrayFloat (7 significant digits)±1.2×10^-38 to ±3.4×10^38new Float32Array([3.134, 1.618, -0.5])
    9Float64ArrayDouble (16 significant digits)±5.0×10^-324 to ±1.8×10^308new Float64Array([2.78, -12.35, 99.9])
    10BigInt64ArrayBig signed integer-2^63 to 2^63 − 1new BigInt64Array([-9071954740991n, 9719925474991n])
    11BigUint64ArrayBig unsigned integer0 to 2^64 – 1new 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
    1ConstructorIt returns an array buffer constructor.
    2byteLengthIt returns the byte length of the TypedArray.
    3maxByteLengthIt returns the maximum byte length to expand the size of the TypedArray.
    4resizableTo 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.MethodsDescription
    1from()It returns a new Array instance.
    2of()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.MethodsDescription
    1at()It returns an element in the typed array that matches the given index.
    2copyWithin()It returns a modified TypedArray without changing the length of the original TypedArray.
    3entries()It returns a new array iterable object.
    4every()It returns true if all elements in the typed array pass the test implemented by the callback function, and false otherwise.
    5fill()It returns the modified typed array, that is filled with the specified value.
    6filter()It returns a new copy of a typed array that includes only the elements that pass the test.
    7find()It returns the first element is TypedArray that satisfied the provided test function, ‘undefined’ otherwise.
    8findIndex()It returns an index of the first element is TypedArray that satisfied the provided test function, ‘-1’ otherwise.
    9findLast()It returns the last element in the typed array that satisfies the provided testing function, ‘undefined’ if not found.
    10findLastIndex()It returns the last element in the typed array that passes the test, -1 if not found.
    11forEach()It returns none(undefined).
    12includes()It returns ‘true’ if searchElement is found in the typed array; ‘false’ otherwise.
    13indexof()It returns the first index of the searchElement.
    14join()It returns a string by joining all the elements of a typed array.
    15Keys()It returns a new iterable iterator object.
    16lastIndexof()It returns the last index of the searchElement in a typed array. If the search element is not present, it returns -1.
    17map()It returns a new typed array by executing the callback function on each element.
    18reduce()It returns a value that outputs from running the “reducer” callback function to completion over the entire typed array.
    19reduceRight()It returns a value that results from the reduction.
    20reverse()It returns the reference of the original typed array in reversed order.
    21set()It returns none(undefined).
    22slice()It returns a new typed array containing the extracted elements of the original typed array.
    23some()It returns true, if atlesat one element in typed array pass the test implemented by provided function; false otherwise.
    24sort()It returns the reference of the same typed array in sorted order.
    25subarray()It returns a new TypedArray object.
    26toLocaleString()It returns a string that represents the elements of the typed array.
    27toReversed()It returns a new typed array containing the elements in reversed order.
    28toSorted()It returns a new typed array with the elements sorted in ascending order.
    29toString()It returns a string that represents the elements of the typed array.
    30values()It returns a new array iterable object.
    31with()It returns a new typed array with the element at the index replaced with the specified value.

    Examples

    Example 1

    We used the Int8Array to create a TypedArray in the example below. We passed the array containing the multiple elements as an object constructor.

    In the output, you can see that if any input element is greater than the 8-bit number, the constructor function automatically enforces it to the 8-bit number.

    <html><body><p id ="output"></p><script>const array =newInt8Array([1000,200,30,40]);
    
      document.getElementById("output").innerHTML ="The array is: "+ array;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The array is: -24,-56,30,40
    

    Example 2

    In the example below, we used the Float32Array() constructor function to create a TypedArray. It is used to store the 32-bit floating point numbers.

    Also, you can access or update TypedArray elements as the normal array.

    <html><body><p id ="output"></p><script>const array =newFloat32Array([100.212,907.54,90,14562547356342.3454]);
    
      array[2]=23.65;// Updating the 3rd element of the array
      document.getElementById("output").innerHTML ="The array is: "+ array;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The array is: 
    100.21199798583984,907.5399780273438,23.649999618530273,14562546941952

  • The Reflect Object

    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
    1apply()To invoke a function.
    2construct()Allows to specify the different prototypes.
    3defineProperty()Allows to insert or edit object property.
    4deleteProperty()Allows to delete the object property.
    5get()To get a value of the property.
    6getOwnPropertyDescriptor()Allows to get the descriptor of the object.
    7getPrototypeOf()To get the prototype of the object.
    8has()To check whether the property exists in the object.
    9isExtensible()Allows to check whether the object is extensible.
    10ownKeys()Returns the own keys of the targeted object and ignores the inherited keys.
    11preventExtensions()To prevent the extension of the object.
    12set()To set the value to the object property.
    13setPrototypeOf()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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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.";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The Car object contains the name.