Polymer: Computed properties and “undefined”

I love the concept of computed bindings: Polymer automatically recalculates computed properties whenever a dependent value changes. This provides excellent decoupling of properties.

For example: Let’s say we want to show Child vs. Adult based on the age property. If the user didn’t provide the age, we just call it a Big secret.

Here is the code:

properties: {
age: Number,
prettyAge: {
type: String,
computed: '_computePrettyAge(age)'
}
},
_computePrettyAge: function(age) {
if (!age) return 'Big secret';
return age < 18 ? 'Child' : 'Adult';
}

This works great as long as age is initialized with a value different than undefined. Otherwise, Polymer’s computed binding wouldn’t trigger the method _computePrettyAge, keeping the prettyAge property undefined as well.

So how do we get the prettyAge even if the age property is undefined? The solution is actually pretty simple: Define a value for the property prettyAge itself:

properties: {
age: Number,
prettyAge: {
type: String,
computed: '_computePrettyAge(age)',
value: 'Big secret'
}
},
_computePrettyAge: function(age) {
if (!age) return 'Big secret';
return age < 18 ? 'Child' : 'Adult';
}

Now, prettyAge has the value Big secret until age is set for the first time. Once set, _computePrettyAge is triggered, and generates the right value.

So what’s happening if the age becomes again undefined? In that case, Polymer’s computed binding will actually be triggered and set prettyAge back to Big secret.

Happy coding!

Want to learn more about Polymer? Have a look to all our Medium posts on Polymer.