JavaScript Objects

Lesson

JavaScript Objects

Objects is the single most important feature of JavaScript Language. In Objects, it contains properties. We define key-value pairs which means that each value has a name which is called the key. We can use Objects to group together different variables that belong together and have no particular order.

Properties

Properties are the value associated with the JavaScript Objects. The example below, we create an Object called ‘person’, in ‘person’ object, we can have the name, age, school, and gender as the person’s properties.

Getting properties

We simply can use ‘.’ to access objects properties . Just like the example below!

alert(person.name);

Another way to access objects properties is by using [], see the example below:

alert(person[‘birthYear’]);

Also we can create a new variable that is able to access the specific properties, this might be useful sometimes!

let x = ‘birthYear’;
alert(person);

Object mutation

Mutation in JavaScript means change in the form of the original data.

we can change it directly like this:

person.birthYear = 2020;   //mutate the age object
person['school'] = "csns"; //mutate the school object

Create a New Object

Let person2 = new Object();
person2.name = "Ben";
person2.school = "BYOD";
person2.birthYear = 2008;
person2.gender = "Male";

alert(person2);

Methods

The functions that we create attach to the objects, we called it Method. So why and how we need methods? Here is the example of using a method into the object.

let person = {
	name: 'Amy',
	birthyear: 2010,
	school: 'CSNS',
	gender: 'Female',
	calculateAge: function(birthyear) { //this is the method of the person
			return 2020 - birthyear;
	}
};

alert(person.calculateAge(2010));

What is this?

We must notice ‘2010’ here that we passed in as an argument of the function is actually already defined in the person Object itself. So instead of having to pass it into the function again, we can access that property from the method inside of the objects by using ‘this”.

“this” means this object, the current object, here is how we call the method:

calculateAge: function() { //this is the method of the person
	return 2020 - this.birthyear;
}

Now we want to store this result into the person Object, we could use:

person.age = person.calculateAge();
//Or
Let age = person.calculateAge();

We can access a property in the current object, that means we can also set it!

@

Not recently active