A Comprehensive Guide to JavaScript - Part 3 - Objects

kgprajwal

Prajwal

Posted on July 5, 2020

A Comprehensive Guide to JavaScript - Part 3 - Objects

Objects

An object is a non-primitive data type. It is a collection of related data or functionality. These consists of several variables and functions which are called properties and methods of the object.
Example:

var Student = {name: "Prajwal", age: "20"}; // Student object with two properties
Enter fullscreen mode Exit fullscreen mode

Almost everything in javascript is an object. All javascript values such as Booleans, Strings, Numbers, Maths, Dates, Regular Expressions, Array and Functions are all objects.

Creating an Object

  • Using an object literal:
var Car = {company: "Lamborghini", name: "Aventador", year: "2020"};
Enter fullscreen mode Exit fullscreen mode
  • Using new keyword:
var Car = new Object();
Car.company = "Lamborghini";
Car.name = "Aventador";
Car.year = "2020";
Enter fullscreen mode Exit fullscreen mode

Adding New Properties to an Object

  • Dot notation
Car.color = "royal blue"
Enter fullscreen mode Exit fullscreen mode
  • Bracket notation
Car['color'] = "royal blue"
Enter fullscreen mode Exit fullscreen mode

Deleting Properties from an Object

delete Car.color;
Enter fullscreen mode Exit fullscreen mode

Adding a Method to an Object

Car.fullname = function() {
    return this.company + " " + this.name;
};
Enter fullscreen mode Exit fullscreen mode

Built-In Constructors

  • New Object object
var a = new Object();
Enter fullscreen mode Exit fullscreen mode
  • New String object
var a = new String();
Enter fullscreen mode Exit fullscreen mode
  • New Number object
var a = new Number();
Enter fullscreen mode Exit fullscreen mode
  • New Boolean object
var a = new Boolean();
Enter fullscreen mode Exit fullscreen mode
  • New Array object
var a = new Array();
Enter fullscreen mode Exit fullscreen mode
  • New Regular Expression object
var a = new RegExp();
Enter fullscreen mode Exit fullscreen mode
  • New Function object
var a = new Function();
Enter fullscreen mode Exit fullscreen mode
  • New Date object
var a = new Date();
Enter fullscreen mode Exit fullscreen mode

Using this for Object References

The keyword this is used in javascript to refer to the properties of the current object.

var Car1 = {name: "Lamborghini"};
var Car2 = {name: "Ferrari"};
function display() {
    console.log("Car name is: ", this.name);
}
Car1.display = display;
Car2.display = display;
Car1.display(); // Lamborghini
Car2.display(); // Ferrari
Enter fullscreen mode Exit fullscreen mode

Objects play a very important role in javascript and I hope you've understood them well by now.

Thank You!

💖 💪 🙅 🚩
kgprajwal
Prajwal

Posted on July 5, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related