Ankur Singh

Frontend Developer Software Developer || Fascinated by tech trends || Building usable systems that work on web and mobile.

JavaScript Object

JavaScript objects are similar to objects in real life which consist of different attributes and properties. Objects are used to store keyed collections of various data and more complex entities. In JavaScript, objects penetrate almost every aspect of the language.  

An object can be created brackets  {  }  with an optional list of properties. A property is a “key: value” pair, where “key” is a string (also called a “property name”), and “value” can be anything.

How to create javascript object

let user = {  
  name: "XYZ",  // key = "name" and value = "XYZ"
  age: 25,       // key = "age" and value = 25
  role: “admin”  // key = “role” and value = “admin”
};

The last property in the list may end with a comma. That is called a “trailing” or “hanging” comma. Makes it easier to add/remove/move around properties, because all lines become alike.

Brackets {…} are called an object literal.

We can add, remove and read files from an object any time.

Access Property of an object

 ObjectName.propertyName   

You can access property and values by using the dot notation like.

// access property values of the object
    console.log(user.name) // output= XYZ
    console.log(user.age) // output= 25
    console.log(user.role) // output= admin

Add data into object

user.isAdmin = true;

Delete data from object

To remove a property, we can use  delete operator:   

delete user.age;

We can also use multiword property names, but then they must be quoted.

let user = {  
  name: "XYZ", 
  age: 25, 
  role: “admin”,
  ”Like Works”: false, // multiword property name must be quoted.
};

For multiword properties, the dot access doesn’t work. It gives the syntax error.

The dot requires the key to be a valid variable identifier. That contains no spaces, does not  start with a digit and does not  have any special characters except “ $ “ and  “ _ ”.

There’s a way to access this  “square bracket notation” that works with any string.

let user = {};
// add
user[”Like Works”] = true;

// access
alert(user[”Like Works”]); // true

// delete
delete user[”Like Works”];

How to check property exist or not

An object’s feature is that it’s possible to access any property. There will be no error if the property doesn’t exist! Accessing a non-existing property just returns undefined. It provides a very common way to test whether the property exists or not.

There also exists a special operator “in” to check for the existence of a property.

Syntax:    “key” in object

For Example:

let car = { name: "Swift", Model:”Vdi” };
alert( "name" in car ); // true, user.age exists
alert( "asd" in car ); // false, user.blabla doesn't exist

Note: On the left side of “ in ” there must be a property name. That’s usually a quoted string.

The “for…in” loop

To walk over all keys of an object, there exists a special form of the loop: for..in. syntax is:

for (key in object) {
  // executes the body for each key among object properties
}
For example:
let car = { name: "Swift", Model:”Vdi”, isLatestModel: true };

for (let key in car) {
  //Find keys
  console.log( key );  // name, age, isAdmin
  // values for the keys
  console.log( car[key] ); // Swift, Vdi, true
}

Some methods of objects

1.  Object.assign()

Copies the values of all enumerable own properties from one or more source objects to a target object.

Syntex:  Object.assign(target, …sources)

Example:

const targetObject = { a: 1, b: 2 };
const sourceObject = { b: 4, c: 5 };

const newObject = Object.assign(targetObject,sourceObject);
console.log(targetObject);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(newObject);
// expected output: Object { a: 1, b: 4, c: 5 }

2. Object.create()

    Creates a new object with the specified prototype object and properties.

    Syntex: Object.create(proto, [propertiesObject])

    Example:

Example:
    const person = {
  name:"john",
  isHuman: false,
  age: 30
};
const newObject = Object.create(person);
console.log(newObject.name); // output is john
console.log(newObject.age); // output is 30

3. Object.defineProperty()

Adds the named property described by a given descriptor to an object.

Syntex : Object.defineProperty(objectName, property, descriptor)

Example:

const objectA = {};
Object.defineProperty(objectA, 'age', {
  value:50,
  writable: false
});
objectA.age= 30;
// throws an error in strict mode
console.log(objectA.age);
// expected output: 50

4. Object.freeze()

    Freezes an object. Other code cannot delete or change its properties.

    Syntex:  Object.freeze(obj)

    Example:

const object1 = {
          age: 20
};

Object.freeze(object1);

object1.age = 33;
// Throws an error in strict mode

console.log(object1.age);
// expected output: 42

Reference:  

  1. JavaScript.info
  2. JavaScript | MDN
Share