🔗What is object Literals ?
ES6 allows declaring object literals by providing shorthand syntax for initializing properties from variables , defining function methods. It also enables the ability to have computed property keys in an object literal definition..
🔗Object Property Initializer
Before ES6, the object literal is a collection of name-value pairs. For example,
jsfunction user(firstName, lastName) {return {firstName: firstName,lastName: lastName,};}
The above syntax looks repetitive because the firstName and lastName mentioned twice in keys and values of properties.
ES6 allows you to eliminate the duplication when a property of an object is the same as the local variable name by including the name without a colon and value.
jsfunction user(firstName, firstName) {return {firstName,firstName,};}
🔗Computed property name :-
Before es6 we could use squre bracket [] notation to enable the computed property names for
the object properties.
jsvar user = {name: "Sumit",age: 20,};var profession = "prof_name";user[profession] = "Web developer";console.log(user);
ES6 introduced a new feature 'computed property names,' which is a part of object literal syntax, and it uses the square bracket []
notation. It allows us to put
an expression within the square
jsvar profession = "prof_name";var user = {name: "Sumit",age: 20,[profession]: "Web developer",};console.log(user);
🔗Concise method syntax :-
Before ES6, defining a method for an object literal, we must have to specify the name and definition of a complete function as represented in the following example:
jslet user = {firstName: "Sumit",lastName: "Harijan",fullName: function () {return this.firstName + " " + this.lastName;},};console.log(user.fullName()); // Sumit Harijan
ES6 uses shorthand syntax, which is also known as the concise method syntax for making a method of the object literal concise by removing the colon (:) and the function keyword.
jslet user = {firstName: "Sumit",lastName: "Harijan",fullName() {return this.firstName + " " + this.lastName;},};console.log(user.fullName()); // Sumit Harijan