# JS Tip of the Day: Computed Properties

**URL:** <https://forum.kirupa.com/t/js-tip-of-the-day-computed-properties/643108>\
**Category:** web dev\
**Created:** [April 28, 2020, 11:45am UTC](https://forum.kirupa.com/t/js-tip-of-the-day-computed-properties/643108 "2020-04-28T11:45:09Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![senocular](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/senocular/32/7217_2.png) [@senocular](https://forum.kirupa.com/u/senocular)\
**Post date:** [April 28, 2020, 11:45am UTC](https://forum.kirupa.com/t/js-tip-of-the-day-computed-properties/643108/1 "2020-04-28T11:45:09Z")

</div>

**Computed Properties**  
Version: ES2015  
Level: Beginner

When using bracket notation (`[]`) to access properties in an object, you can use any expression to represent the property key. This allows you to dynamically determine a key at runtime.

It used to be that this would only work off of existing objects, but starting with ES2015 this notation also became supported in object literals and class bodies. Properties using this syntax are known as computed properties.

```javascript
let length = 0;
let fakeArray = {
    [length++]: 'one',
    [length++]: 'two',
    [length++]: 'three',
    length
};

console.log(fakeArray.length); // 3
console.log(fakeArray[1]); // two

```

Some properites require using computed property syntax, particularly those using symbols as keys. We’ve seen this before with symbols like `Symbol.toStringTag`.

```javascript
class Named {
    get [Symbol.toStringTag] () {
        return 'Named'
    }
}

let named = new Named();
console.log(named.toString()); // [object Named]

```

This particular example uses defines a getter, but with class fields (stage 3 proposal), you can also define it as an instance field directly in the class body.

```javascript
class Named {
    [Symbol.toStringTag] = 'Named';
}

let named = new Named();
console.log(named.toString()); // [object Named]

```

Computed properties cannot be used with the property shorthand syntax that allows you to match keys and variables of the same name in scope. Attempting to do so will result in an error.

```javascript
let prop = 'value';
let key = 'prop';

let obj = {
    [key] // SyntaxError (not same as prop: prop)
};

```

More info:

- [Object initializer on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer)
- [Class fields on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Class_fields)
