Javascript Objects
Written By: Avinash Malhotra
Updated on
What is Object
Everything in JavaScript is an Object as JavaScript is an Object Based Language. Any datatype in Javascript is either primitive or an Object. All reference data like Arrays, Objects, Map, Set and Functions are also Objects but they are built-in objects in javascript.
Objects are just like an entity with properties and values. Object's values can be of any datatype. Like a car is an object which can have properties like length, width, height, power, torque and methods like start(), reverse() etc.
JavaScript Objects are collection of Multiple data types inside a single variable, just like Arrays, but Arrays use index notation and Objects use key-value pair.
Built-in Objects in JavaScript
- console
- document
- window
- screen
- navigator
- history
- location
How to declare Object in JavaScript
Objects in javascript can be declared using curly brackets {}. We can also use new Object() constructor function to declare Objects. Both {} and new Objects() works same. new Object() is constructor form, and curly brackets {} is literal form of JS Objects.
JavaScript Object Literal
const car={}; // Object
JavaScript Object Constructor
const car=new Object(); // Object
Check Object datatype
Objects are Reference data types. typeof
operator will return "object" for both Arrays and Objects. To check datatype of an object, use instanceof(Object) method. instanceof() method will check whether the passed value is an Object or not.
instanceOf() array, object and function is true. This means instanceof can check datatype of all reference data types (Arrays, Objects and Functions).
using typeof
typeof operator is mainly used to check datatype of string, number, boolean, undefined and function. For others, typeof will return object
object
const car={};
console.log(typeof car);
using instanceof
instanceof operator check the object is instance of Class or function. It is true for all reference data types.
true
const car={};
console.log(car instanceof(Object));
using constructor.name
constructor.name is recommended to check data type of object.
Object
const car={};
console.log(car.constructor.name);
using Object.prototype.toString.call()
Object.prototype.toString.call can also be used to check data type of object.
'[object Object]'
const car={};
console.log(Object.prototype.toString.call(car));
- instanceof of Arrays, Objects and Functions is Object.
- For Arrays, use Array.isArray().
- For functions, use typeof operator.
Traversal values of Object
To check element inside Object, we can call object.property or object followed by property in brackets. To find first element, call array[0]. This index notation starts from 0 to array.length-1.
const user={
"full-name":"Avinash Malhotra",
profile:"FullStack Developer",
location:"Noida, Delhi NCR",
pincode:201301,
};
user.profile; // return "FullStack Developer"
user.location; // return "Noida, Delhi NCR"
user.pincode; // return 201301
or
user["full-name"]; // return "avinash malhotra"
user["profile"]; // return "FullStack Developer"
Object.freeze()
Object.freeze() method freezes an object and the object becomes immutable. This can prevent further modification in object, like change in properties value, adding or removing properties etc.
const user={
name:"avinash malhotra",
profile:"Frontend Developer",
location:"Noida, Delhi NCR",
pincode:201301,
};
Object.freeze(user);
user.pincode=112233; // false
Check Object is frozen
To check an object id frozen, use Object.isFrozen( object ). This will return boolean.
const user={
name:"avinash malhotra",
profile:"Frontend Developer",
location:"Noida, Delhi NCR",
pincode:201301,
};
Object.isFrozen(user); // false
Object.freeze(user);
Object.isFrozen(user); // true
Check property in object
An Object can have both custom properties and prototype properties (like toString, toLocaleString etc). in operator is used to check whether given property or method (function) exists or not. in operator return boolean value, either true or false. See example
const user={
name:"avinash malhotra",
profile:"Frontend Developer",
location:"Noida, Delhi NCR",
pincode:201301,
};
"location" in user; // returns true
"toString" in user; // returns true
"age" in user; // returns false
hasOwnProperty
The hasOwnProperty property check whether the property is his own property or global property of all JS Objects. It returns boolean value, true or false. in operator returns true for all properties, including global. See example
const user={
name:"avinash malhotra",
profile:"Frontend Developer",
location:"Noida, Delhi NCR",
pincode:201301,
};
user.hasOwnProperty("pincode"); // returns true
user.hasOwnProperty("profile"); // returns true
user.hasOwnProperty("toString"); // returns false
Object.hasOwn
Object.hasOwn methods is introduced in ES13 which is the replacement of hasOwnProperty. This methods require two parameters, first name of object and second property name, both as strings.
const user={
name:"Avinash Malhotra",
profile:"Frontend Developer",
location:"Noida, Delhi NCR",
pincode:201301,
};
Object.hasOwn(user,"pincode"); // returns true
Object.hasOwn(user,"toString"); // returns false
Add and remove property in objects
An JS Object can add and remove properties in object. Even if object is already declared, still we can add and properties in object
Add Property in Object
const user={
"full-name":"avinash malhotra",
profile:"FullStack Developer",
location:"Noida, Delhi NCR",
pincode:201301,
};
user.country="India";
Remove Property in Object
const user={
"full-name":"avinash malhotra",
profile:"FullStack Developer",
location:"Noida, Delhi NCR",
pincode:201301,
};
delete user["full-name"];
Change Property value in Object
const user={
"full-name":"avinash malhotra",
profile:"FullStack Developer",
location:"Noida, Delhi NCR",
pincode:201301,
};
user.pincode=110001;
Get All properties of Object
To get all properties of object, for in loop is required. for in loop can access all properties inside object and array.
For in can get both own and inherited properties. Inherited means prototype properties on Object Class.
name - avinash malhotra profile - FullStack Developer location - Noida, Delhi NCR pincode - 201301
const user={
name:"avinash malhotra",
profile:"FullStack Developer",
location:"Noida, Delhi NCR",
pincode:201301
};
for( let i in user){
console.log(i + " - " + user[i]);
}
Object Methods
Objects can have both properties and methods. For object methods, we have to assign function to object property and use return value as output.
this keyword in value of object will refer to current object, i.e car.
102.85714285714286 bhp/ton
129.14285714285714 nm/ton
const car={
name:"swift",
power:90,
torque:113,
weight:875,
powerToWeight:function(){return this.power/this.weight * 1000},
torqueToWeight:function(){return this.torque/this.weight * 1000}
};
console.log(car.powerToWeight()+ " bhp/ton");
console.log(car.torqueToWeight() + " nm/ton");
Object Methods in es6
In ES6, methods are still functions, but can be defined using simple syntax.
102.85714285714286 bhp/ton
129.14285714285714 nm/ton
const car={
name:"swift",
power:90,
torque:113,
weight:875,
powerToWeight(){return this.power/this.weight * 1000},
torqueToWeight(){return this.torque/this.weight * 1000}
};
console.log(car.powerToWeight() + " bhp/ton");
console.log(car.torqueToWeight() + " nm/ton");
use getter in Object
get is used to convert Object Method to property.
102.85714285714286 bhp/ton
129.14285714285714 nm/ton
const car={
name:"swift",
power:90,
torque:113,
weight:875,
get powerToWeight(){return this.power/this.weight * 1000},
get torqueToWeight(){return this.torque/this.weight * 1000}
};
console.log(car.powerToWeight + " bhp/ton");
console.log(car.torqueToWeight + " nm/ton");
In the object example, we had a car name swift with 90bhp power and 113Nm Torque. The weight of car is 875kg.
To calculate powerToWeight ratio, we have to divide car power by car weight and then multiply by 1000 and for torqueToWeight ratio, we have to divide car torque by car weight and then multiply by 1000.
use setter in Object
set keyword binds an object property to a function to be called to set that property. set is supported in both Objects and Classes.
[500000, 600000]
const car={
name:"swift",
power:90,
torque:113,
weight:875,
prices:[],
set setPrice(p){ this.prices.push(p) }
};
car.setPrice=500000;
car.setPrice=600000;
console.log(car.prices);
Object.Keys
Object.keys() method return an array of given objects keys.
['name', 'power', 'torque', 'weight']
const car={
name:"swift",
power:90,
torque:113,
weight:875
};
let keys=Object.keys(car);
Object.values
Object.values() method return an array of given objects values.
['swift', 90, 113, 875]
const car={
name:"swift",
power:90,
torque:113,
weight:875
};
let keys=Object.values(car);
Object.entries()
Objects,entries() methods convert an JavaScript Object to Array with each key-value pair as elements in nested array. This method is also useful to count number of key-values in Object.
[ [ "name","swift"], ["power",90], ["torque",113], ["weight",875] ]
const car={
name:"swift",
power:90,
torque:113,
weight:875,
};
console.log(Object.entries(car));
Check length of Object
In JavaScript length is the property of Arrays, Strings and Functions. To check length of Object, use Object.entries(obj).length. Object.entries(obj) will convert Object to Array and then we can check length property of array.
4
const car={
name:"swift",
power:90,
torque:113,
weight:875,
};
console.log(Object.entries(car).length);
Iterate over Object.entries
We can also use for-of loop to iterate over array build using Object.entries(). This is similar to using for-in loop for Object, but for-in will iterate over both own and prototype properties.
name swift
power 90
torque 113
weight 875
const car={
name:"swift",
power:90,
torque:113,
weight:875,
};
let obj=Object.entries(car);
for(let [i,j] of obj){
console.log(i,j);
}
Assign
Object.assign(obj1, obj2) method copy all own properties of second argument (object) to first argument (object). This will modify first argument object with new properties.
{name:"swift", power:90, torque:113, weight:875}
const car={
name:"swift",
weight:875,
};
const engine={
power:90,
torque:113,
};
Object.assign(car,engine);
console.log(car);