DEV Community

Pranay Rebeyro
Pranay Rebeyro

Posted on

Objects in JavaScript

Object

An Object is a collection of key-value pairs. Each value is stored with a name called a key.It is collection of information in single variable.

Eg:
let student = {
    name: "Pranay",
    age: 21,
    course: "ECE"
};
Enter fullscreen mode Exit fullscreen mode

Accessing Object Values

There are two ways to access object properties.

1. Dot Notation

console.log(student.name);
console.log(student.age); 
// Output: 
Pranay
21
Enter fullscreen mode Exit fullscreen mode

2. Bracket Notation
Bracket notation is useful when the property name is stored in a variable.

console.log(student["course"]);
// Output: ECE
Enter fullscreen mode Exit fullscreen mode

Adding a New Property
We can add new properties anytime.

let student = {
    name: "Pranay",
    age: 21,
    course: "ECE"
};
student.city = "Chennai";
console.log(student);
Enter fullscreen mode Exit fullscreen mode

Updating a Property
We can change an existing value.

let student = {
    name: "Pranay",
    age: 21,
    course: "ECE"
};
student.age = 22;
console.log(student.age);
Enter fullscreen mode Exit fullscreen mode

Deleting a Property
Use the "delete" keyword to delete the object.

let student = {
    name: "Pranay",
    age: 21,
    course: "ECE"
};
delete student.course;
console.log(student);
Enter fullscreen mode Exit fullscreen mode

Core Components of Object
1. Properties: Variable Declaration
2. Methods: Function Declaration

let student = {
    name: "Pranay",

    greet: function () {
        console.log("Hello!");
    }
};

student.greet();
// Output: Hello!
Enter fullscreen mode Exit fullscreen mode

This Keyword
Inside an object, this refers to the current object.

let student = {
    name: "Pranay",

    greet: function () {
        console.log("Hello " + this.name);
    }
};

student.greet();
// Output: Hello Pranay
Enter fullscreen mode Exit fullscreen mode

Top comments (0)