JavaScript Objects

JavaScript Objects

Javascript Object is a basic but necessary array of knowledge for a programmer. In this article, we will learn about the concept of an object. How to initialize and add properties/methods to an object? Stay tuned for the content below.

What are JavaScript objects?

In Javascript, an object is an abstract concept, used to represent objects through which we can add properties and methods to that object.

We have some objects like Date, Number available. In addition to these objects, the programmer can create an object of their own.

Each object value is written as a name:value pair

 For example, the following statement is used to create an object named WebsiteIT and it stores two names properties:

  • name (whose value is the string LearnShareIT)
  • year (valid as number 2022)
var WebsiteIT = {name:"LearnShareIT", year:”2022”}

Declare object in JS

You can use one of three ways to declare objects in Javascript:

  • Using keyword {}
  • Using new Object() keyword
  • Using static method

Here is an example of object creation in Js:

// literal
const rose = { }

// constructor
const pencil = new Object();

// static method
const computer = Object.create({ })

When declaring objects, you need to avoid declaring other types of Js objects, including: string, boolean or number.

For example:

a = new String();        // Declares a as a String object
b = new Number();        // Declares b as a Number object
c = new Boolean();       // Declares c as a Boolean object

The above declaration will make your program more confusing and easy to get errors.

Object properties in JS

Properties are the characteristics (can be understood as variables) that need to be stored in the object. For example, with the Students object, we need the following properties:  name, age, amount,…

Accessing an object’s property returns the value of that property. To access an object’s properties, we use the following syntax:

objectName.propertyName

or

objectName["propertyName"]

For example:

var Students = { 
                firstName: "Huang", 
                lastName: "Kai", 
                age: 18, 
                getFullName: function () { 
                    return this.firstName + ' ' + this.lastName 
                } 
            };

person.firstName; // returns Huang
person.lastName; // returns Kai

Note: In a regular object, this refers to the object on which it is defined.

Methods of Objects in JS

Methods are actions (can be understood as functions) of the object. For example, in the Car object, we have two methods:

  • addCar()
  • validateCar()

Accessing the object’s method will help the statements in the method to be executed. To access the method of the object, we use the following syntax:

object name.method name()

For example:

//Object initialization function
function Car(color, year) {
   this.color = color;
   this.year = year;
   this.changeColor = function (color) {
     this.color = color;
   }
}

//Create object
var p = new car("Blue", 2022);

Manipulating properties and methods of objects in JS

After creating an object, we have two basic uses, that is, calling and assigning data to properties and methods. But if we consider all aspects, we have the following common operations:

  1. Assign value to attribute
  2. Get the value of the attribute
  3. Calling the method

1. Assign value to attribute

To assign a value to a property, we just do it using the = operator in the same way as assigning a value to a variable.

Car.color = "Green;

But if you call from a function in the object then you can use this keyword.

var Car = {
     color : "",
     addCar : function(){
         this.color = "green";
     }
};

2. Get the value of the attribute

To get the property value, we do the same as manipulating variables.

var color = Car.color;

If calling from a function in the object, you can use this keyword.

var Car = {
     color : "",
     addCar : function(){
         var color = this.color;
     }
};

Besides, you can also change the object’s property value using the above access and assign a new value to that property.

let myCar = {
   color: "green",
   year: "2022",
};

myCar.color = "green";
myCar["year"] = "2019";

console.log(Car.color); // green
console.log(myCar["year"]); // 2019

3. Calling the method

Similar to the property we call normally.

Car.addCar();

Call in the object’s function:

var Car = {
     color : "",
     addCar : function(){
         this.validateCar();
     },
     validateCar : function(){
         // by some thing
     }
};

4. Attribute Delete

If you want to delete certain properties, use the delete keyword. When you delete properties, these properties do not exist in the object anymore, or their values become undefined.

For example:

let Car = {
   color: "green",
   year: "2022",
};

delete Car.color;
console.log(myComputer.color); // undefined

Check the existence of the attribute

When a property does not exist in the object, its value is undefined.

But you cannot use this method to check the existence of a property in an object. As most likely, the property’s value is actively assigned to undefined.

To solve this problem, you can use the in operator with the following syntax:

"key" in object;

Example usage in:

let Car = {
   color: undefined,
};

console.log("color" in car); // true
console.log("year" in car); // false

Note: the element to the left of the in operator is the property name, usually enclosed in “” or ”. The return result is a boolean value with true for existence, false for non-existent.

Array containing objects

When working with objects, you can completely create an array of objects in Js. This will be beneficial and save time for programmers when having to manipulate a lot of data.

For example:

// Car object
var Car = {
     color : "",
     year : "",
     type : "",
};
 
// Initialize array
var cars = [];
 
// Assign value to array element
Cars[0] = Cars;
 
// Call to property
Cars[0].color = "green";
alert(cars[0].color);

Object contains Object

In addition, in a program that declares variables, you can also nest this object in another variable object. Examples are as follows:

Concatenate Car properties into an Info object.

var Car = {
     info : {
         color : "",
         year : "",
         type : "",
     }
};

So, above we have helped you have the most overview of object JS. This is the most basic content when approaching Javascript. Learning and mastering the fundamentals will help you to write and handle programs easily.

Below we have compiled a list of tutorials related to JavaScript Objects that may be of interest to you:

Leave a Reply

Your email address will not be published. Required fields are marked *