Object Literals - Javascript

In this tutorial we are going to discuss about object literals in javascript but we are not going in details of object oriented programming in javascript and won't discuss about concepts like constructors etc.

Let's create an student object

const student = {
  "name"  : "Jack Ryan",
  "class" : "HighSchool",
  "subjects" : ["Arts", "Commerce", "Science"],
  "address" : {
    "city" : "Fremont",
    "state" : "California",
  }
}

console.log(student.name);
console.log(student["name"]);
console.log(student.subjects[0]);
console.log(student.address.state);

Output:

 

You can also define a function inside object property (see getRank function)

const student = {
  "name"  : "Jack Ryan",
  "class" : "HighSchool",
  "subjects" : ["Arts", "Commerce", "Science"],
  "address" : {
    "city" : "Fremont",
    "state" : "California",
  },
  "getRank" : function() {
    return 2;
  }
}

console.log(student.getRank());

Output: 2

 

None