DEV Community

Cover image for Javascript Objects
Manikandan K
Manikandan K

Posted on

Javascript Objects

Object

  • Non-primitive data type.
  • Stores multiple collections of data.
  • Simply, js Object is a collection of key-value pairs.
key: value
Enter fullscreen mode Exit fullscreen mode

Image description

Syntax

const object_name = { 
    key_1: value_1,
    key_2: value_2,
    key_n: value_n
}
Enter fullscreen mode Exit fullscreen mode

Object Creation

const person = {
  firstName: 'Manikandan',
  lastName: 'MK',
  age: 24,
};

console.log(typeof person); // object
console.log(person); // { firstName: 'Manikandan', lastName: 'MK', age: 24 }
Enter fullscreen mode Exit fullscreen mode

Explanation:
An object is a collection of key-value pairs.

   person                    - object name,
   firstName, lastName, age  - key/name. (left side)
   Manikandan, mk, 24        - value. (right side)
Enter fullscreen mode Exit fullscreen mode

Key-value pairs are called properties.

ACCESSING OBJECT

1. Dot Notation

Syntax:

Object_name.key
Enter fullscreen mode Exit fullscreen mode

Example:

const person = {
  firstName: 'Manikandan',
  lastName: 'MK',
  age: 24,
}; 

console.log(person.firstName); // Manikandan
Enter fullscreen mode Exit fullscreen mode

Image description

2. Bracket Notation

Syntax:

  ObjectName["propertyName"]  (property name is nothing key name)
Enter fullscreen mode Exit fullscreen mode
Example: 
const person = {
    firstName: 'Manikandan',
    lastName: 'MK',
    age: 24
    }

    console.log(person['firstName']);   // Manikandan
Enter fullscreen mode Exit fullscreen mode

Image description

Nested Object

A nested Object is nothing but an Object containing another object.

Example:

const person = {
  firstName: 'Manikandan',
  lastName: 'MK',
  age: 24,
  physicalDetails: {
    height: 170,
    weight: 70,
  },
};

console.log(person.physicalDetails); // { height: 170, weight: 70 }
console.log(person.physicalDetails.height); // 170
Enter fullscreen mode Exit fullscreen mode

Image description

Add Property from an Object
Image description

Remove Property from an Object

Image description

Top comments (0)