In This article, we will cover what is object literal and constructor.
Lets dive in !
object literal
object literal Syntax
const objectName = {
member1Name: member1Value,
member2Name: member2Value,
member3Name: member3Value,
};
eg
const person = {
name: ["Bob","Smith"],
age: 32,
bio: function () {
console.log(`${this.name[0]} ${this.name[1]} is ${this.age} years old.`);
},
introduceSelf: function () {
console.log(`Hi! I'm ${this.name[0]}`)
}
}
We can replace the function syntax like this
const person = {
name: ["Bob", "Smith"],
age: 32,
bio() {
console.log(`${this.name[0]} ${this.name[1]} is ${this.age} years old.`);
},
introduceSelf() {
console.log(`Hi! I'm ${this.name[0]}.`);
},
};
This type of object creation is called object literal, This syntax is useful when we want to transfer a series of structured, related data items.
dot notation
we can access or set object's property and method using dot notation.
Eg, In our person's object
Access
console.log(person.name);
//results ["Bob", "Smith"]
person.bio();
//results Bob Smith is 32 years old
Setting
person.name = ["Shawn", "Yeo"]
console.log(person.name);
//["Shawn", "Yeo"]
person.run = () => {console.log("I am running")}
person.run();
//I am running
Bracket notation
we can also use bracket notation to access and set property of our object.
Access
const name = person["name"]
//set
person["name"] = ["shawn", "yeo"]
Normally dot notation is preferred over bracket notation, however if object property name is held in variable you can use bracket notation to access the value.
const person = {
name: ["Bob", "Smith"],
age: 32,
};
function logProperty(propertyName) {
console.log(person[propertyName]);
}
logProperty("name");
// ["Bob", "Smith"]
logProperty("age");
// 32
constructors
object literal is useful when you quickly need a related data to be passed over but when we need a shape of object to be recreate over and over, we use constructor.
constructor syntax
function Person(name) {
this.name = name;
this.introduceSelf = function () {
console.log(`Hi! I'm ${this.name}.`);
};
}
//creating person object using contructor
const person_1 = new Person("shawn");
const person_2 = new Person("johna");
By convention, constructor start with a capital and when we create instance of an object we use key word new
Thank you for reading ! we have covered concepts of Object literal, how we could access and set the values using dot notation and bracket notation. And how to use constructor to create object shape and the instance of an object.
Reference
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics
Top comments (0)