Objects in JavaScript

JavaScript object is a non-primitive datatype that allows you to store multiple collections of data. For example;

const student = {
    firstName: 'ram',
    age: 10
};

Declaration

The syntax of how to declare an object is;

const object_name= {
key1: value1,
key2: value2
}

For example;

const student={
name: "Ruby",
age: 21
};

JavaScript Object Properties

In JavaScript, "key: value" pairs are called properties. For example,

let person = { 
    name: 'John',
    age: 20
};

Accessing Object Properties

You can access the value of a property by using its key.

  • Using dot Notation

Here's the syntax of the dot notation.

objectName.key
const student={
name: "Ruby",
age: 21
};
//accessing 
console.log( student.name );//  Ruby

Using bracket Notation

Here is the syntax of the bracket notation.

objectName["propertyName"]

For example,

const person = { 
    name: 'John', 
    age: 20, 
};

// accessing property
console.log(person["name"]); // John

JavaScript Nested Objects

An object can also contain another object. For example,

// nested object
const student = { 
    name: 'John', 
    age: 20,
    marks: {
        science: 70,
        math: 75
    }
}

// accessing property of student object
console.log(student.marks); // {science: 70, math: 75}

// accessing property of marks object
console.log(student.marks.science); // 70

JavaScript Object Methods

In JavaScript, an object can also contain a function. For example,

const person = {
    name: 'Sam',
    age: 30,
    // using function as a value
    greet: function() { console.log('hello') }
}

person.greet(); // hello

Here, a function is used as a value for the greet key. That's why we need to use person.greet() instead of person.greet to call the function inside the object.

Happy Learning!