Guide to JavaScript Objects and Object Methods with easy examples
I'll start this article with a question. So, Why would your website look different from one browser to another? What lies at the center of these browser incompatibility issues?
The Answer is the Browser engine. You can think of the browser engine as the heart of a browser. it helps to present the content of a website by understanding the HTML, CSS, and JavaScript written on your web page. Sounds pretty simple, right? but it isn't, because browser engines are uniquely designed for every browser, which leads to cross-browser compatibility issues.
A browser engine comprises two engines, which came into the picture after the birth of Javascript,
Rendering Engine
JavaScript Engine
Rendering Engine
It is responsible for the layout of the website on the screen. When we say the page is rendered correctly on the screen, we are actually appreciating the rendering engine's capabilities.
Here is a list of rendering engines produced by major web browser vendors.
Blink – Used in Google Chrome, and Opera browsers.
WebKit – Used in Safari browsers.
Gecko – Used in Mozilla Firefox browsers.
Trident – Used in Internet Explorer browsers.
EdgeHTML – Used in Edge browsers.
Presto – Legacy rendering engine for Opera.
JavaScript Engine
As the name suggests, it helps to interpret the JavaScript code of the website before rendering it. Browser engine uses them as a compiler to drive faster results with improved performance.
Below is the list of JavaScript engines produced by major web browser vendors.
V8 – Used with Blink
Nitro – Used with Webkit
SpiderMonkey – Used with Gecko
Chakra – Used with Trident & EdgeHTML
This discussion was important because, with JavaScript Engine in your web browsers, you can run your js codes. All you have to do is just right-click and go to Inspect and you'll find Console and Source.
Now, let's get into javascript objects.
Object in JavaScript
The Object type represents one of JavaScript's data types. Apart from Primitive Values of JavaScript -> Null, Undefined, Boolean, Number, BigInt, String, and Symbol everything else is an object in JavaScript.
You will find this statement "Nearly all objects in JavaScript are instances of Object". Let's see how to create an object in javascript.
Creating an Object in JavaScript
There are different ways to create objects,
Object Literals
Constructor Functions
Object.create Method
Let’s look at each one of them in detail.
Object Literal
It is the easiest way to create a JavaScript Object. Object literals are a comma-separated list of key-value pairs wrapped in curly braces. Here, you are defining as well as creating an object in one statement.
const userProfile = { fName: "Saloni", age: 10 };
console.log(userProfile); // This will log {fName: 'Saloni', age: 10}
You can also make an object definition span multiple lines, to make it more readable.
The below example creates an object named userProfile with three properties firstName, lastName, dateOfBirth, and fullName() method.
You can also add a method to an object literal. The fullName() method takes two properties of the userProfile object, firstName, and lastName. Then returns the user’s full name. The this
keyword refers to the current object of which properties the method is calling.
const userProfile01 = {
firstName: "Bill",
lastName: "Gates",
dateOfBirth: 1955,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
console.log(userProfile01);
You can also create an empty JavaScript object, and then adds properties to it as shown below,
const userProfile = {};
userProfile.name = "Saloni";
userProfile.age = 10;
console.log(userProfile); // {name: 'Saloni', age: 10}
Constructor Function
You can create an object using the constructor function. You define an object type without any specific values. Then, you create new object instances and populate each of them with different values.
You can create a new JavaScript object using new Object(), and then add properties to it as shown below,
const userProfile02 = new Object();
userProfile02.name = 'Elon Musk';
userProfile02.netWorth = '14,380 crores USD';
console.log(userProfile02) // This will log {name: 'Elon Musk', netWorth: '14,380 crores USD'}
In the above example, a userProfile02 object is defined by using the new operator and then two properties name and netWorth are defined with some values. The values of the properties are added by the object instance.
Object.create() Method
You can also create new objects using the Object.create() method.
You can create just as below,
const object1 = Object.create();
The Object.create() is a static method that will allow you to use an existing object literal as the prototype of a new object you create.
You basically pass an object into Object.create() method when you want to copy/inherit the properties of an existing object, but it is rarely used.
const powers = {
fly: true,
cordinate: Math.round(Math.random() + 2)
}
const superPowers = Object.create(powers);
console.log(superPowers); // This will log {} (an empty object)
In the above example, an object called powers is defined with two properties. Then, an object called superPowers is created using the Object.create()
method and the "powers" object is passed as an argument. The superPowers object is a standalone object, but it inherits the properties of the "powers" object.
But, the above code will log an empty object, So Where are those inherited properties?
If you are trying this code on your browser, you can simply see the inherited properties by clicking on the arrow ➤ in the [[Prototype]]: Object, as shown below. Basically, it throws the inherited properties into the Prototype(which will be discussed separately)
You can also see this in your code editor by using Object.getPrototypeOf()
method.
console.log(Object.getPrototypeOf(superPowers));
// This will log {fly: true, cordinate: 2}
JavaScript Object Methods
- Object.assign()
This method is used to copy the values of all enumerable own properties from one or more source objects to a target object.
Syntax: Object.assign(target_object, source_objects)
const obj1 = {a: 1, b: 2, c: 3};
const obj3 = {x: 1, y: 2, z: 3};
const obj2 = Object.assign({c: 4, d: 5}, obj1);
const obj4 = Object.assign({x: 36, y: 69}, obj3);
console.log(obj2.c, obj2.d); // This will log 3 and 5
console.log(obj4.x, obj4.y); // This will log 1 and 2
- Object.create()
This method is used to create a new object with the specified prototype object and properties. You can create an object without a prototype by Object.creates (null), check above examples.
- Object.defineProperty()
This method defines a new property directly on an object and returns the object. To change the flags, you can use Object.defineProperty.
Syntax: Object.defineProperty(object, property, descriptor)
Let's see examples for a better understanding.
const object1 = Object.create({});
Object.defineProperty(object1, 'property1', {
value: 'Saloni'
});
console.log(object1); // This will log {property1: 'Saloni'}
console.log(Object.getPrototypeOf(object1)); // This will log {}
This should work according to the syntax, but we cannot use this, we have to use the get() method here, as shown below.
const object1 = Object.create({});
Object.defineProperty(object1, 'property1', {
get: () => 'Saloni'
});
console.log(object1.property1); // This will log Saloni
- Object.defineProperties()
This method defines new or modifies existing properties directly on an object, and returns the object.
const obj1 = {};
Object.defineProperties(obj1, {
property1: {
get: () => 100
},
property2: {
get: () => 20
}
});
console.log(obj1.property1,obj1.property2);
// This will log 100 and 20
- Object.getOwnPropertyDescriptor()
This method allows you to query the full information about a property and returns a property descriptor for the own property of an object.
const object1 = {
property1: 10
}
const descriptor1 = Object.getOwnPropertyDesciptor(object1,'property1');
console.log(descriptor1.enumerable); // Logs true
console.log(descriptor1.value); // Logs 10
- Object.getOwnPropertyDescriptors()
It returns all own property descriptors of a given object.
One difference between getOwnPropertyDescriptors() and getOwnPropertyDescriptor() method is that getOwnPropertyDescriptors() method ignores symbolic properties.
const object1 = {
property1: 100
};
const descriptors1 = Object.getOwnPropertyDescriptors(object1);
console.log(descriptors1.property1.value); // Logs 22
console.log(descriptors1.property1); // Logs {value: 22, writable: true, enumerable: true, configurable: true}
console.log(descriptors1.property1.writable); // Logs true
- Object.getOwnPropertyNames()
It returns an array of all properties found directly upon a given object, except those non-enumerable properties which use symbols.
const object1 = { 11: 'a', 22: 'b', 33: 'c' };
console.log(Object.getOwnPropertyNames(object1)); // Logs ['11', '22', '33']
Object.getOwnPropertyNames(object1).forEach(function(value, index, array) {
console.log('The value at ' + value + ' is ' + object1[value]);
}); // Logs The value at 11 is a
// The value at 22 is b
// The value at 33 is c
- Object.getOwnPropertySymbols()
It returns an array of all symbol properties found directly upon a given object. It'll return an empty array unless you have set symbol properties on your object.
const object1 = {};
a = Symbol('a');
b = Symbol.for('b');
const objectSymbols = Object.getOwnPropertySymbols(object1);
console.log(objectSymbols); // Logs [] -> empty array
console.log(objectSymbols.length); // Logs 0
object1[a] = 'Hitesh';
object1[b] = 'Saloni';
const objectSymbols = Object.getOwnPropertySymbols(object1);
console.log(objectSymbols); // Logs [Symbol(a), Symbol(b)]
console.log(objectSymbols.length); // Logs 2
- Object.getPrototypeOf()
It returns the prototype or the value of the internal [[Prototype]] property of the specified object.
Eaxample for this one is already shown above with explanation.
const powers = {
fly: true,
cordinate: Math.round(Math.random() + 2)
}
const superPowers = Object.create(powers);
console.log(superPowers); // This will log {} (an empty object)
console.log(Object.getPrototypeOf(superPowers));
// This will log {fly: true, cordinate: 2}
- Object.setPrototypeOf()
It sets the prototype or the internal [[Prototype]] property of a specified object to another object or null.
let human = {
walk() {
return "Can walk";
}
}
let superHuman = {
fly() {
return "Can fly";
}
}
Object.setPrototypeOf(superHuman, human); // Setting prototype of human to superHuman prototype
console.log(superHuman); // Logs {fly: ƒ}
console.log(superHuman.fly);
// ƒ fly() {
// return "Can fly";
// }
console.log(superHuman.walk);
// ƒ walk() {
// return "Can walk";
// }
- Object.is()
This method is used to compare values, it determine whether two values are same.
Object.is(100,100); // Returns true
Object.is('Saloni','Salon') // Returns false
const obj1 = { a: 123 };
const obj2 = { a: 123 };
const obj3 = obj1;
Object.is(obj1, obj1); // Returns true
Object.is(obj1, obj2); // Returns false
Object.is(obj1, obj3); // Returns true
- Object.isExtensible()
It determines if an object is extensible meaning whether it can have new properties added to it.
// New objects are extensible.
const emptyObject = {};
Object.isExtensible(emptyObject); // Returns true
// They can be made un-extensible
Object.preventExtensions(emptyObject);
Object.isExtensible(emptyObject); // Returns false
- Object.freeze()
This method is basically used to prevent the modification of existing properties, attributes, and values. It freezes an object that prevents new properties from being added to it.
const object1 = {
property1: 369
};
const object2 = Object.freeze(object1);
object2.property1 = 33;
console.log(object2.property1); // This will log 369
- Object.isFrozen()
It determines if an object is frozen.
const object1 = {
property1: 36
};
console.log(Object.isFrozen(object1)); // Returns false
Object.freeze(object1);
console.log(Object.isFrozen(object1)); // Returns true
// Frozen objects are also by definition non-extensible.
const frozen = Object.freeze({});
Object.isExtensible(frozen); // Returns false
- Object.seal()
It seals an object which prevents new properties from being added to it and marks allexisting properties as non-configurable.
const object1 = {
property1: 36
};
Object.seal(object1);
object1.property1 = 69;
console.log(object1.property1); // Returns 69
delete object1.property1; // it cannot be deleted when sealed
console.log(object1.property1); // Returns 69
- Object.isSealed()
It determines if an object is sealed.
const object1 = {
property1: 36
};
console.log(Object.isSealed(object1)); // Returns false
Object.seal(object1);
console.log(Object.isFrozen(object1)); // Returns true
// Sealed objects are by definition non-extensible.
const sealed = Object.seal({});
Object.isExtensible(sealed); // Returns false
- Object.preventExtensions()
It is used to prevent any extensions of an object. Basically it prevents new properties from being added to an object ever.
const object1 = {};
Object.preventExtensions(object1);
Object.defineProperty(object1, 'property1', {
value: 42
}); // This will throw TypeError: Cannot define property property1, object is not extensible
- Object.entries()
This method is used to return an array of a given object's own enumerable property [key, value] pairs. The ordering of the properties is the same as that given by looping over the property values of the object manually.
Syntax: Object.entries(obj)
const object1 = { 1: 'a', 2: 'b', 3: 'c' };
console.log(Object.entries(object1)[2]);
// This will log ["3", "c"]
const object1 = { 1: 'a', 2: 'b', 3: 'c' };
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
// This will log
// 1: a
// 2: b
// 3: c
- Object.keys()
It returns an array of a given objects own property names that are enumerable.
const object1 = {
a: 'Hello',
b: 'Good',
c: 'Day'
};
console.log(Object.keys(object1)); // Logs ['a', 'b', 'c']
- Object.values()
It returns an array which contains the given objects own enumerable property values. It return the value in the same order as that provided by a for...in loop.
const object1 = {
rank: 1,
name: 'Saloni',
pass: true
};
console.log(Object.values(object1)); // Returns [1, 'Saloni', true]
Congratulation on getting this far.
Read more about JavaScript Objects from MDN Docs
Subscribe to my newsletter
Read articles from Saloni directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by