Computed Property Names in JavaScript

The Computed Property Name feature allows us to use an expression that returns a valid value as Property Name. We need to enclose the expression inside square brackets( []).

Dynamic Property Name

In the following example, we create a variable author and store Author Name in it.

While creating the book object, we use the author variable inside the []. The JavaScript creates the property Author Name.

This is how dynamic properties were created before ES6.

let author = 'Author Name';
 

let book = {
    [author]: 'Marijn Haverbeke',
};
 

console.log(book[author]); // Marijn Haverbeke

Computed Property Names

Since ES6, we can use the expression directly inside the []. The expression must return a single value. The JavaScript will evaluate the expression and uses the return value to create the property.


let prefix = "Book";
 
let book = {
    [ prefix + "Author"]: 'Marijn Haverbeke',
    [ prefix + "Title"]: "Eloquent JavaScript"
};
 
console.log(book[prefix + "Author"]); // Marijn Haverbeke
console.log(book["BookAuthor"]);      // Marijn Haverbeke
 
//We can also use this. because there is no space in the property name
console.log(book.BookAuthor);        // Marijn Haverbeke

You can also invoke a function inside square brackets.

let prefix = "Book";
 
let book = {
    [ getAuthorName()]: 'Marijn Haverbeke',
    [ prefix + "Title"]: "Eloquent JavaScript"
};
 
function getAuthorName() {
  return prefix+'Author'
}

The following example, dynamically adds the property to object a

let i = 0
let a = {};
  
for (i=0;i<5;i++) {
    a['foo'+i]=i
}

console.log(a)   //{foo0: 0, foo1: 1, foo2: 2, foo3: 3, foo4: 4}

The addProperty takes any object and adds the property passed in its argument.

person = {}


function addProperty(obj, key, value) {
    obj[key] = value
}

addProperty(person, 'firstName', 'Allie') 
addProperty(person, 'lastName', 'Grater') 


console.log(person)  //{firstName: "Allie", lastName: "Grater"}

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top