Objects and Constructors in JavaScript

Sunday, Jan 12, 2020
JavaScript

JavaScript has a built-in flexible and powerful data structure called object. Objects are like Python dictionaries that can contain data of different types in name: value pair format. Objects can be elements of an array and arrays can be elements of objects. This allows us to create data structures of arbitrary complexity.

NOTE: A better way of creating modular objects is to use classes instead.

Furthermore, combining the objects with functions, constructors can be built using which multiple objects of the same type can be created easily. In that sense, constructors are like blueprints for creating objects. Two additional keywords to implement constructors are this and new. Let's see how they work in code.

Program

// objects.js -- program to demo objects and constructors
var topic = { // declared using braces
    name: "history", // format is property: value
    size: 40, // multiple data types can be combined
    grade: 8,
    teachers: ["Ms. Goldilocks", "Mr. Zack"] // values can be arrays
}
console.log(topic);
console.log(topic.name); // values can be accessed by dot notation
console.log(topic["grade"]); // or by [] 
topic.isHard = true; // more properties can be added after object definition
console.log(topic);

// objects can be created using constructors
function Ball(size){ // defining a constructor using function
    this.size = size; // this keyword is used to pass value to specific object
    this.material = "rubber";
    this.rolling = false;
}

var ball_1 = new Ball(12); // new keyword is used to create a new object
console.log(ball_1.rolling);
var ball_2 = new Ball(14);
console.log(ball_2.size > ball_1.size);

Output

{
  name: 'history',
  size: 40,
  grade: 8,
  teachers: [ 'Ms. Goldilocks', 'Mr. Zack' ]
}
history
8
{
  name: 'history',
  size: 40,
  grade: 8,
  teachers: [ 'Ms. Goldilocks', 'Mr. Zack' ],
  isHard: true
}
false
true