# Solving Knockout JS calculated bindings Syntax Error

**Date:** 2014-02-16  
**Author:** Kees C. Bakker  
**Categories:** JavaScript, jQuery  
**Tags:** Knockout  
**Original:** https://keestalkstech.com/solving-knockout-js-calculated-binding-in-the-interface/

![Solving Knockout JS calculated bindings Syntax Error](https://keestalkstech.com/wp-content/uploads/2014/02/753782552_e0a80407bd_b.jpg)

---

Knockout JS does an excellent job in binding the interface with a View Model. Sometimes you'll need some data manipulation before a value can be shown to the users. How would you go about?

A few options come to mind:

Using more complex operations might result in the JavaScript exception: *Uncaught SyntaxError: Unable to parse bindings*.

## Printing the position

Let's say we need to list the position of an object in an observable array, with the following rules:

## First try: wrong way

When I tried to implement this, I used the following - but it did not work:

```html
<span data-bind="text: { 
	var x = $index; 
	x += 1; 
	if(x < 10) x = '0' + x; 
	return x + '.'; 
} "></span>
```

KnockoutJS doesn't know how to parse this and you'll end up with an error.

## **Anonymous function to the rescue**

The trick is to *wrap* it into an anonymous function and *calling* it with the index as a parameter. Because of the nature of this function, we must evaluate the observables that are passed (use `()` to get the value).

```html
<span data-bind="text: 
	(function(i) { 
		i += 1; 
		if(i < 10) i = '0' + i; 
		return i + '.'; 
	})($index());
">
</span>
```

This technique is frequently used in JavaScript to achieve [information hiding](http://en.wikipedia.org/wiki/Information_hiding).
