DEV Community

Harini
Harini

Posted on

Objects in JavaScript

What is Objeccts?

  • Object is a variable that can hold multiple variables.
  • It is a collection of key-value pairs,where each key hass a value.
  • Combination of States(Attributes) and Behavior(Methods).
  • Declare object with the const keyword.

Example

const person = {
  name:"Jack",
  age:41,
  city:"New York"
}
console.log(person.name);
Enter fullscreen mode Exit fullscreen mode

1. Adding new attributes

Example

const person = {
  name:"Jack",
  age:41,
}
person.city = "New York";    //Add attribute
console.log(person.city);
Enter fullscreen mode Exit fullscreen mode

2. Deleting existing attributes

  • The delete keyword deletes a property from an object.

Example

const person = {
  name:"Jack",
  age:41,
  city:"New York"
}
delete person.city;     //Delete attribute
console.log(person);
Enter fullscreen mode Exit fullscreen mode

3. Update

  • Just assign a new value to the same key.
  • Similar to add syntax.

Example

const person = {
  name:"Jack",
  age:41,
  city:"New York"
}
person.age = 42;
console.log(person.age);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)