DEV Community

Cover image for Javascript Objects
Manikandan K
Manikandan K

Posted on

4 3

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay