Ankur Singhal

JavaScript Object

By Ankur Singhal

Last updated cal_iconDecember 15, 2021

JavaScript objects are similar to objects in real life, consisting of different attributes and properties. It is used to store keyed collections of various data and more complex entities. In JavaScript, objects penetrate every aspect of the language and create brackets {} with an optional list of properties. An object contains properties, or key-value pairs, 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. The dot requires the key to be a valid variable identifier, making 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 at 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.is Admin = true.

Delete data from object

We can use the delete operator to remove a property: – delete the user. Age; – We can also use multiword property names, but 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 has no 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

The characteristic of an object is that it is possible to access any property. If the property does not exist, there will be no error. Accessing a non-existing property 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 move over all keys of an object, a special form of loop exists: for..in. The 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 own enumerable 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 }

  1. Object.create()

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

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

    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

  1. Object.defineProperty()

Adds a 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

  1. 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

Get In Touch

How Can We Help ?

We make your product happen. Our dynamic, robust and scalable solutions help you drive value at the greatest speed in the market

We specialize in full-stack software & web app development with a key focus on JavaScript, Kubernetes and Microservices
Your path to drive 360° value starts from here
Enhance your market & geographic reach by partnering with NodeXperts