Saturday, March 30, 2024

What is Javascript Object and Object Methods?

Javascript Object:

As we have already learned that JavaScript variables are containers for data values.

The below code assigns a simple value (Mumbai) to a variable named text:

let text="Mumbai";

Objects are variables too. But objects can contain many values.

The below code assigns many values (Mumbai, Maharashtra, India) to a variable named text:

const text = {name:"Mumbai", state:"Maharashtra", country:"India"};

a) object are used to store collections of data and more complex entities.

b) objects can be created using {...} with optional list of properties, a property is "key": "value" pair.

c) Creating an empty object,

let studentDetail = {};

let studentDetail = new Object();

d) Creating an object with properties,

let studentDetail = {

"name": "Test",

"rollNo": 1,

"Full Name": "Test User"

};

e) To access the property values use dot notation or array notation in case of space in key name as shown below,

studentDetail.name  // dot notation

To access full name use array notation as it has space.

studentDetail[Full Name]   // array notation

f) Adding a value to property,

studentDetail.department = 'Computer Science';

g) We may add comma to last property as shown below.

let studentDetail = {

name: "Test",

rollNo: 1,

};

h) To access the keys use,

Object.keys(studentDetail)

i) Use JSON.stringify to convert object to string

var jsonStrng= JSON.stringify(studentDetail);

console.log(jsonStrng);

"{"name":"Test","rollNo":1,"Full Name":"Test User"}"

j) Use JSON.parse to convert string to object

Object = JSON.parse(jsonStrng);

{name: "Test", rollNo: 1, Full Name: "Test User"}

Object Methods:

An object method is an object property containing a function definition.

const person = {

  firstName: "Farukh",

  lastName: "Haider",

  fullName: function() {

    return this.firstName + " "  + this.lastName;

  }

};

console.log(person.fullName());

Output:

Farukh Haider

How to Access JavaScript Object Properties?

The syntax for accessing the property of an object is:

objectName.property

objectName["property"] 

Let us understand this with an example?

const person = {

  fname:" John",

  lname:" Doe",

  age: 25

};

console.log('person'+person.fname);

console.log('person'+person["fname"]);

Output:

person John

person John

We can also iterate over object as shown below:

for (let x in person) {

  console.log(person[x]);

}

Output:

John

Doe

25

No comments:

Post a Comment