Alexa Metrics

JavaScript Intermediate Series: JavaScript Objects

2018-11-08
Image of icons showing different objects in JavaScript

JavaScript is a widespread programming language. A strong understanding of its concepts is critical to use it to its full potential. Objects are one such concept.


What are objects?

Imagine creating records of students in a school. Each student will have some properties that make them unique and some functions they can do or be involved with in the school. Properties can include the student’s name, their age, and other defining characteristics. Methods can include enroll, withdraw, take test, and so on.


As we have discussed previously, JavaScript value containers are called variables. Objects are also variables, but they can hold many values at the same time. For example, a typical student might look like this:


var student = {Name:"John", age:10, gender:"male"};


You can use spaces and line breaks according to your preference, also known as convention. The values in this object are usually written as comma-separated name value pairs.

The above example can be re-written as:

var student = {

Name:"John",

age:10,

gender:"male"

};

Accessing an Object:

How do you access the values within the object? This can be done in one of two ways. The first is:

student.age;

The second is:

student[age];


Next, let’s move on to methods. Methods are functions/procedures that can be embedded in an object. These are the actions that manipulate an object’s data.


An example of an object method can be something like:


var student = {

name: "John",

age: 10,

introduce: function() {

return “My name is ” + this.name;

}

};


What is This?

The “this” keyword is analogous to the “self” keyword in Python. Both are pointers used to access an object’s properties and manipulate them.

In the previous example, this.name will return the name value within the object.


Accessing the object methods can be the same as accessing its properties. For example, you could access the student object’s introduce method like this:


student.introduce()


There is a lot more to cover in JavaScript, and we will continue this series in later articles. Meanwhile, you can start practicing what you have already learned. Start learning with RoboGarden now, register for free.


JavaScript Series Intermediate JavaScript

RELATED BLOGS

Start JavaScript coding

Let's start JavaScript coding with RoboGarden learning journey.

Canada Flag Privacy Policy Terms of Use
Got an invite