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:
- Assign value to attribute
- Get the value of the attribute
- 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:
- Check if an object is empty in JavaScript
- Check if a key exists in a javaScript object
- Check if an Object Property is Undefined in JavaScript
- Convert an Object to JSON String using JavaScript
- Add a key/value pair to an object in javascript
- Cannot convert undefined or null to Object in JavaScript
- How to Rename an Object’s Key in JavaScript
- How to get an Object’s Class in JavaScript
- Access the First Property of an Object in JavaScript
- How to get the Class Name of an Object in JavaScript
- Remove all Undefined Values from an Object in JavaScript
- Convert an Object to a Map using JavaScript
- Sum the Values of an Object using JavaScript
- Get the Max/Min Date in Array of Objects in JavaScript
- Remove Empty String Values from an Object using JavaScript
- Check if Object is of type Set in JavaScript
- Get the Min and Max Values in an Object in JavaScript
- Get the Last item in an Object in JavaScript
- How to Update a const Object in JavaScript
- Get an Object’s Value by Index in JavaScript
- Swap the Keys and Values in an Object in JavaScript
- Access an Object Property with a Hyphen in JavaScript
- Cannot assign to read only property of Object in JavaScript
- Check if all Values in an Object are True in JavaScript
- Get an Object’s Values as Array in JavaScript
- Set all Values in an Object to Null using JavaScript
- How to call a Function inside an Object in JavaScript
- Get a Random Property from an Object in JavaScript
- Get an Object’s Value by Variable Key in JavaScript
- Loop through Object in Reverse Order using JavaScript
- Access an Object Key that Contains a Space in JavaScript
- Convert an Object to a Query String using JavaScript
- Convert a Map to an Object in JavaScript
- Sort the Keys of an Object in JavaScript
- Sort an Array of Objects by Date property in JavaScript
- Get an Object’s Key by its Value using JavaScript
- Sum a Property in an Array of Objects in JavaScript
- Increment a Value in an Object using JavaScript
- Update an Object’s Property in Array of Objects in JS
- How to get the Length of an Object in JavaScript
Hi guys, wellcome to LearnShareIt. I’m Tiffany and I’m also who responsible for the quality of this website’s content. I previously worked on software development projects for ten years as a developer. Hopefully, our project will bring a lot of value to the community.
Job: Programmer/Project management
Major: IT
Programming Languages: Python, C, HTML, MySQL, SQL Server, C#, C++, Javascript, CSS, Java, VB