“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.

Creating Object

Objects in JavaScript can be created in multiple ways

const User = {}

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
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

const car = {
name : "carName" ,
model : "DummyModel" ,
showModelName : function(){
console.log(`Model Name : ${this.model}`);
}
}

We can retrieve the value of a property using 2 different syntaxes

→ The first is dot notation:

car.name //"carName"
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();