Category: Object Oriented JavaScript

https://zain.sweetdishy.com/wp-content/uploads/2026/01/coding-1.png

  • JavaScript – 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,}

    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.

  • JavaScript – 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.

  • JavaScript – 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 +"<br>"+"Book author is : "+ myBook.author +"<br>"+"Total pages : "+ myBook.pages;</script></body></html>

    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 +"<br>"+"Book author is : "+ book.author;</script></body></html>

    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 +"<br>"+"Book author is : "+ myBook.author +"<br>";</script></body></html>

    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 },})
    • {} − 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 +"<br>"+"Book author is : "+ myBook.author +"<br>";</script></body></html>

    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 +"<br>"+"Book author is : "+ myBook.author +"<br>"+"Book price is : "+ myBook.price +"<br>";</script></body></html>

    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.}</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 +"<br>"+"Book author is : "+ myBook.author +"<br>"+"Book price is : "+ myBook.price +"<br>";</script></body></html>

    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 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.