JavaScript Objects

JavaScript is an object oriented language. In JavaScript we can define our own objects and assign methods, properties to it.
In JavaScript objects are also associative arrays (or) hashes (key value pairs). Assign keys with obj[key] = value or obj.name = value.

  • Remove keys with delete obj.name
  • Iterate over keys with for(key in obj),
  • Iteration order for string keys is always in definition order, for numeric keys it may change.

Object Creation

let user = new Object(); // "object constructor" syntax
let user = {};  // "object literal" syntax

Usually, the figure brackets {...} are used. That declaration is called an object literal.

Properties

let user = {     // an object
  name: "Keshab",  // by key "name" store value "Keshab"
  age: 60        // by key "age" store value 60
};

Reading Properties

// get fields of the object:
alert( user.name ); // Keshab
alert( user.age ); // 60
// get fields of the object:
alert( user["name"] ); // Keshab
alert( user["age"] ); // 60

Adding Properties

user.isAdmin = true;
user["isAdmin"] = true;

To remove a property, we can use delete operator:

delete user.age;

Existence check

There will be no error if the property doesn’t exist! Accessing a non-existing property just returns undefined.

let user = { name: "Keshab", age: 30 };

alert( "age" in user ); // true, user.age exists
alert( "blabla" in user ); // false, user.blabla doesn't exist

Object reference

Object reference Avariable which is assigned to object actually keeps reference to it. It acts like a pointer which points to the real data. Using reference variable we can change the properties of object. Variable is actually a reference, not a value when we pass an object to a function.

let user = { name: "Keshab" };

let admin = user; // copy the reference

Example

let user = { name: 'Keshab' };

let admin = user;

admin.name = 'Rajesh'; // changed by the "admin" reference

alert(user.name); // 'Rajesh', changes are seen from the "user" reference

Const object

An object declared as const can be changed.

const user = {
  name: "Keshab"
};

// Error (can't reassign user)
user = {
  name: "Rajesh"
};

Leave a Reply

Your email address will not be published. Required fields are marked *