“Objects” in JavaScript
What is an Object?
→ Any value that’s not of a primitive type (a string, a number, a boolean, a symbol, null, or undefined) is an object.
→ For Instance: Array, functions are also treated as an object by JavaScript.
Creating Object
Objects in JavaScript can be created in multiple ways
- Here’s how we define an object:
const User = {}
This is the object literal syntax.
2. You can also initialize an object using the new keyword. here the function acts as a constructor for that object. In this, we can initialize the value.
Read this blog to know more about this keyword in JavaScript
const User = function(name , courseCount){
this.name = name ;
this.courseCount = courseCount ;
}//without using new keyword
const newUser1 = User("newUser1" , 2) ;console.log(newUser1) ; //OUTPUT //undefined
→ This is because this is a normal function that refers to global object/window object, hence “name” and “coureCount” are not defined globally undefined.
→ To overcome this we use the new keyword to create an object, here new is used because this tells the JS engine that now the User has a separate scope that is pointing to “newUser1”.
const User = function(name , courseCount){
this.name = name ;
this.courseCount = courseCount ;
}const newUser1 = new User("newUser1" , 2) ;console.log(newUser1) ;//OUTPUT //User{
// name:"newUser1",
// courseCount:2
//}
Object Properties
→ Objects have properties, which have a label associated with a value to it
→ The value of a property can be of any type, which means that it can be an array, a function, and it can even be an object, as objects can nest other objects
For Instance,
const car = {
name : "carName" ,
model : "DummyModel" ,
showModelName : function(){
console.log(`Model Name : ${this.model}`);
}
}
here “name” is the label and “carName ”is the value, similarly, we can have the values as an object, function, array …
We can retrieve the value of a property using 2 different syntaxes
→ The first is dot notation:
car.name //"carName"
→ The Second is to use Square brackets
car['name'] //"carName"
Object Methods
Functions can be assigned to function properties, and in this case, they are called methods.
const car = {
name : "carName" ,
model : "DummyModel",
showModelName : function(){
console.log(`Model Name : ${this.model}`);
}
}car.showModelName();
In this, we can access name and model properties value by this keyword.
Note: Arrow function can’t be used as a method inside an object this is because Arrow Function has its own scope