JavaScript Objects

JavaScript Objects

A brief introduction to Objects In JavaScript.

ยท

6 min read

Objects in javascript are one of the non-primitive datatypes which allow us to store multiple values in key-value pairs. These key-value pairs are known as properties. The key is also called as property name and the value is also called the property value. In objects, values can be of any datatype, it can be string, numbers, boolean, function, array, etc, the main difference between a primitive datatype and an object is that a primitive datatype can store values of only a single datatype but in the object, we can store the value of any type. Key in objects can only be a string if we use the key of any other datatype then it is converted to a string. Enough of the talking let's take a look at an object.

let student = {
  name: "John Kumar",
  age: 20,
  subjects: ["Maths", "Science", "Computer Science"],
  isPresent: true,
};

In the above example student is an object, and it has four properties. name ,age subjects isPresent are key or we can call it property name and John Kumar 20 ["Maths", "Science", "Computer Science"] isPresent are values of different types. Anything left to the colon : is key and the right to the colon is value.

Creating Objects

For creating objects in javascript there are many different syntaxes, but in this article, we are going to talk about two, object literal and object constructor.

Object Literal

We can create an empty object with just a pair of curly brackets {} , this syntax of creating an object is known as Object Literal.

// object literal syntax
const student = {} // an empty object

Object Constructor

We can also create a new object with the help of the constructor function and new keyword, this method of creating an object is known as an Object constructor.

// object constructor syntax
const teacher= new Object(); // an empty object

Adding Properties to an Object

We have created two objects student and teacher let's now add some properties to these objects. The properties of an object are the same as the variable except that they are linked to objects rather than being confined to a specific scope. The properties of an object define its characteristics.

let Student= {}; // empty object with Object literal syntax

// Adding properties to student object

Student.name = "John Kumar";
Student.age = 20;
Student.subjects = ["Maths", "Science", "Computer Science"];
Student.isPresent = true;
// another syntax to add properties
Student["class"] = "VII";
Student["phone number"] = 9898989898;

// displaying the Student Object
console.log(Student);
// Output
/*
{
  name: 'John Kumar',
  age: 20,
  subjects: [ 'Maths', 'Science', 'Computer Science' ],
  isPresent: true,
  class: 'VII',
  'phone number': 9898989898
}
*/

// teacher Object

const Teacher= new Object(); // empty object with Object Constructor syntax
//Adding properties to teacher Object
Teacher.name = "Tony Prasad";
Teacher.age = 50;
Teacher.teachers = ["Algorithms", "Maths"];
Teacher.isPresent = true;
// another syntax
Teacher["department"] = "Computer Science";
Teacher["phone number"] = 9898989898;
console.log(Teacher);
// Output
/* 
{
  name: 'Tony Prasad',
  age: 50,
  teachers: [ 'Algorithms', 'Maths' ],
  isPresent: true,
  department: 'Computer Science',
  'phone number': 9898989898
}
*/

Accessing Properties from an Object

We can access the properties of an Object using their properties name, there are two syntaxes to do that, let's talk about them one by one.

Dot Notation

This is the most used syntax.

objectName.propertyName

// Display student name from student object 
console.log(Student.name);
// Display student subjects from student object
console.log(Student.subjects);
// Display student phone number from student object

// We can't do that using dot notation, when we are using
// multi word property name we can't use dot notation syntax to do that.
// that's why multi word property name is not recommended use camelCase or 
// sanke_case property name

Bracket Notation

objectName["propertyName"]

// Display student name from student object 
console.log(Student["name"]);

// Display student subjects from student object
console.log(Student["subjects"]);

// Display student phone number from student object
console.log(Student["phone number"]);

Object Methods

What are the methods? - Nothing to worry about methods are functions defined inside an object, yes we can define a function inside an object, let's do that. Let's define some methods inside an Object, but first, let's talk about this keyword.

this is a special keyword in Javascirpt, It refers to an Object but depends on where it's being used. If this keyword is being used in an object's methods then this refers to the current object, if this keyword is being used alone then it refers to global object.

I know this small introduction will not clear your confusion about this, I will talk more about this in the below example which would make more sense, also I will leave some link to resources at the end of this article so that you can understand it better.

Syntax 1

// We can define Methods directly inside an Object
const Student = {
  name: "John Kumar",
  age: 20,
  subjects: ["Maths", "Science", "Computer Science"],
  isPresent: true,
  class: "VII",
  "phone number": 9898989898,
  sayHi: function () {
    console.log(`Hello ${this.name}`); // here this refers to the Student Object
  },
};

// Calling the sayHi Method
Student.sayHi(); // sayHi is a function so we need to call it using ()

Syntax 2

let Student = {}; // empty object

// Adding different properties to it
Student.name = "John Kumar";
Student.age = 20;
Student.subjects = ["Maths", "Science", "Computer Science"];
Student.isPresent = true;
Student["class"] = "VII";
Student["phone number"] = 9898989898;

// Adding sayHi method to Student Object
Student.sayHi = function () {
  console.log(`Hello ${this.name}`); // here this refer to Student Object
};

// Calling the sayHi Method
Student.sayHi(); // sayHi is a function so we need to call it using ()

Syntax 3

// We can declare an independent function
function displayAge() {
  console.log(`${this.name} is ${this.age} years old`); // 

}

// Assigning it to different Object

// Assigning displayAge method to Student Object we defined earlier
Student.displayAge = displayAge;

// Assigning displayAge method to Teacher Object we defined earlier
Teacher.displayAge = displayAge;

// Calling the displayAge method from Student Object
Student.displayAge();

// Calling the displayAge  method from Teacher Object
Teacher.displayAge();

take a look at the displayAge function from the above example, here this will refer to object with which function displayAge will be used, if displayAge function will be used with Student object then this will refer to Student object and if displayAge function will be used with Teacher object then this will refer to Teacher object.

Deleting Object Property

To remove a property from the object we use delete operator.

delete Student.name; // will delete name property from the student object.

Conclusion

That's it for this article we will learn more about objects when we talk about Prototypes.

Resources to Explore More:

Did you find this article valuable?

Support Ankit Kumar by becoming a sponsor. Any amount is appreciated!