Javascript
Think of JavaScript objects as if you were building a car. A car is not just a single entity but a combination of various parts, each with its unique role. Similarly, a JavaScript object is a container that holds different pieces of information and functionalities related to a particular concept or thing. In a car, features like color, model, and year are its properties. In JavaScript, properties are bits of information that describe the object.
Why we are using Objects in Javascript?
Objects in JavaScript serve as a cornerstone for structuring and organizing code. They provide a way to group related data and functions, which helps code reusability and maintainability. Imagine if you had to manage various pieces of information about a student—name, age, grades, and attendance—without the concept of objects. It would be chaotic and challenging to maintain.
There are two main types of objects: built-in objects and user-defined objects.
Built-in objects come with the language, such as Math, Date, and Array.
On the other hand, user-defined objects allow developers to create their own object types.
Now, there are 3 methods for creating objects in JavaScript:
Object Literal:
In this method Property and values are separated by Colon (:)
let car = { make: "Toyota", model: "Camry", year: 2022 };
Object Constructor:
We have to create a function with arguments to create an object.
function Person(name, age) {
this.name = name;
this.age = age;
}
let person1 = new Person("Alice", 25);
Here Person is a Function with name and age as arguments. This
is a keyword used to refer current object.
Object.create() Method:
There is a method called .create to create an Object
let animal = Object.create(null);
animal.type = "Dog";
Let’s consider a real-life scenario to illustrate the concept. Imagine you are developing an application for a school. Instead of handling each piece of information separately, you can use a JavaScript object to represent a student:
Example of an Object with relating to real life
// Creating a Student Object
let student = {
firstName: "John",
lastName: "Doe",
age: 20,
grades: [85, 90, 75, 95],
attendance: {
totalDays: 100,
daysPresent: 90,
},
calculateAverage: function () {
// Method to calculate the average grade
let total = this.grades.reduce((sum, grade) => sum + grade, 0);
return total / this.grades.length;
},
updateAttendance: function (daysAttended) {
// Method to update attendance information
this.attendance.daysPresent = daysAttended;
},
};
In this example:
firstName
, lastName
, age
: These represent basic information about the student.grades
: An array to store the student’s grades.attendance
: An object with properties totalDays
and daysPresent
to manage attendance.calculateAverage
: A method that calculates the average grade of the student based on the grades array.updateAttendance
: A method that allows updating the number of days the student has attended.Now, let’s explore how you might use this object:
// Accessing Properties
console.log(student.firstName); // Output: John
console.log(student.grades); // Output: [85, 90, 75, 95]
// Accessing Nested Property
console.log(student.attendance.totalDays); // Output: 100
// Calling Methods
console.log(student.calculateAverage()); // Output: 86.25
// Updating Property
student.age = 21;
// Updating Nested Property
student.updateAttendance(95);
// Adding New Property
student.course = "Computer Science";
console.log(student.course); // Output: Computer Science
Objects can also have methods—functions associated with them. This adds a layer of functionality to your objects.
For Example:
Using the same example of student, we can use method like this,
// Using Object.keys() to get property names
const propertyNames = Object.keys(student);
console.log(propertyNames);
// Output: ["firstName", "lastName", "age", "grades", "attendance", "calculateAverage", "updateAttendance"]
// Using Object.values() to get property values
const propertyValues = Object.values(student);
console.log(propertyValues);
// Output: ["John", "Doe", 20, [85, 90, 75, 95], { totalDays: 100, daysPresent: 90 }, calculateAverage(), updateAttendance()]
// Using Object.entries() to get key-value pairs
const keyValuePair = Object.entries(student);
console.log(keyValuePair);
// Output: [["firstName", "John"], ["lastName", "Doe"], ["age", 20], ["grades", [85, 90, 75, 95]], ["attendance", { totalDays: 100, daysPresent: 90 }], ["calculateAverage", ƒ], ["updateAttendance", ƒ]]
// Using Object.hasOwnProperty() to check if a property exists
const hasLastName = student.hasOwnProperty("lastName");
console.log(hasLastName);
// Output: true
// Using Object.freeze() to freeze the student object
Object.freeze(student);
// Trying to add a new property will not work
student.newProperty = "New Value";
console.log(student.newProperty);
// Output: undefined
// Using Object.seal() to seal the student object
Object.seal(student);
// Trying to delete the 'age' property will not work
delete student.age;
console.log(student.age);
// Output: 20
Other the built-in methods available for Javascript Object are here:
Method | Returns |
---|---|
Object.keys(obj) | An array of strings representing the object’s property names. |
Object.values(obj) | An array of values corresponding to the object’s properties. |
Object.entries(obj) | An array of arrays, each containing a key-value pair. |
Object.assign(target, source1, source2, ...) | The modified target object. |
Object.create(proto, [propertiesObject]) | A new object with the specified prototype. |
Object.freeze(obj) | The frozen object. |
Object.seal(obj) | The sealed object. |
Object.getOwnPropertyNames(obj) | An array of strings representing the object’s property names. |
Object.getOwnPropertyDescriptor(obj, prop) | An object with properties configurable, enumerable, value, writable, get, and set. |
Object.defineProperty(obj, prop, descriptor) | The modified object. |
Object.defineProperties(obj, props) | The modified object. |
Object.getPrototypeOf(obj) | The prototype of the object. |
Object.setPrototypeOf(obj, prototype) | The modified object. |
Object.hasOwnProperty(prop) | true if the object has the property; otherwise, false. |
Object.is(obj1, obj2) | true if the values are the same; otherwise, false. |
Object.values(obj) (ES2017) | An array of values corresponding to the object’s properties. |
These methods enhance our ability to work with and manipulate objects in JavaScript effectively.
JavaScript objects are our coding companions, bring versatility to our code. With methods like Object.keys()
, Object.values()
, and protective spells such as Object.freeze()
, we navigate, explore, and reuse our code. Whether crafting websites, apps, or games, JavaScript objects are the backbone of the code.