DEV Community

Veera Ganapathi
Veera Ganapathi

Posted on

Javascript Object

What are JavaScript Objects?

  • Objects are variables that can store both values and functions.
  • Values are stored as key:value pairs called properties.
  • Functions are stored as key:function() pairs called methods.
const students = {
  name:"abc",
  age:18,
  dept:"cs"
};
Enter fullscreen mode Exit fullscreen mode

Object Properties

  • Properties are key:value Pairs.
  • A JavaScript object is a collection of properties.
  • Properties can be changed, added, and deleted.

Access Properties

  • Dot notation
  • Bracket notation
  • Expression
// objectName.property
let age = students.age;

//objectName["property"]
let age = students["age"];

//objectName[expression]
let age = students[x];
Enter fullscreen mode Exit fullscreen mode

Changing Properties

You can change the value of a property:

const person = {
  name: "vijay",
  age :  50
};
person.age = 10;
console.log(person.age);


output:
10
Enter fullscreen mode Exit fullscreen mode

Add New Properties

You can add a new property by simply giving it a value.

const person = {
  name: "vijay",
  age: 50
};
person.nationality = "English";
console.log(person.nationality);

output:
English
Enter fullscreen mode Exit fullscreen mode

Delete Properties

The delete keyword deletes a property from an object.

const person = {
  name: "vijay",
  age: 50
};
delete person.age;
console.log(person);

output:
vijay
Enter fullscreen mode Exit fullscreen mode

The delete keyword deletes both the value and the property.
After deleting, the property is removed. Accessing it will return undefined.

Nested Objects

Property values in an object can be other objects.

const students = {
  name:"abc",
  age:18,
  subject:{
      sub1:"cs",
      sub2:"maths",
      sub3:"cc"
}
};
console.log(students.subject.sub2;);

output:
maths
Enter fullscreen mode Exit fullscreen mode

Object Methods

Methods are actions that can be performed on objects. Methods are functions stored as property values.

const students = {
  name:"abc",
  age:18,
  fullName: function() {
    return students.name + " " + students.age;
  }
};
let full=students.fullName();
console.log(full);
Enter fullscreen mode Exit fullscreen mode

Object Constructors

Sometimes we need to create many objects of the same type. To create an object type we use an object constructor function. It is considered good practice to name constructor functions with an upper-case first letter.

function Person(first, age) {
  this.name = first;
  this.age = age;

}

// Create a Person object
const myFather = new Person("vijay", 50);
const myMother = new Person("thi", 45);
console.log(myFather);
console.log(myMother);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)