Comparing Currency Formatting in JavaScript and Go: A Case Study
Tags: javascript, go, programming, tutorial
Published: 2023-11-24 13:28:52

In the world of web development, presenting financial information in a clear and standardized way is crucial for a positive user experience. Currency formatting is a common task, and different programming languages offer various approaches to achieve this. In this article, we'll compare the implementation of a currency formatting function in JavaScript and Go, using the same case study.

## The Case Study Function

Let's consider a simple currency formatting function named `formatPrice`. The function takes a numeric value and returns a formatted string representing the currency. We'll look at the JavaScript version implemented using TypeScript and its equivalent Go implementation.

### JavaScript (TypeScript) Implementation

```typescript
const formatPrice = (amount: number | null | undefined): string => {
  const _amount = amount ?? 0;
  return new Intl.NumberFormat("en-NG", {
    style: "currency",
    currency: "NGN",
  }).format(_amount);
};

export default formatPrice;
```

### Go Implementation

```go
package main

import (
	"fmt"
	"text/template"
)

func FormatPrice(amount float64) string {
  const currencyTemplate = "₦{{printf \"%.2f\" .}}"
  tmpl, err := template.New("currency").Parse(currencyTemplate)
  if err != nil {
    panic(err)
  }
  var result string
  err = tmpl.Execute(&result, amount)
  if err != nil {
    panic(err)
  }
  return result
}

func main() {
  price := 1500.0
  formattedPrice := FormatPrice(price)
  fmt.Println(formattedPrice) // Output: ₦1,500.00
}
```

## Key Differences and Considerations

### 1. Language Syntax and Features

- **JavaScript (TypeScript):**
  - Uses TypeScript, a superset of JavaScript with static typing.
  - Utilizes the nullish coalescing operator (`??`) for default value assignment.
  - Leverages the Internationalization API for number formatting.

- **Go:**
  - A statically-typed language with a different syntax compared to JavaScript.
  - Provides a simpler default value assignment without the need for the nullish coalescing operator.
  - Uses the `text/template` package for string formatting.

### 2. Error Handling

- **JavaScript (TypeScript):**
  - Error handling is implicit in the use of the Internationalization API.
  - The function returns a string, and any errors in formatting are handled internally.

- **Go:**
  - Explicit error handling is required using the `err` variable.
  - In the provided example, errors are handled by panicking, but in production code, a more robust error-handling strategy should be implemented.

### 3. Ecosystem and Use Cases

- **JavaScript (TypeScript):**
  - Widely used for web development, especially on the client side.
  - Extensive ecosystem with various libraries and frameworks.

- **Go:**
  - Frequently used for backend development and system-level programming.
  - Known for its simplicity, performance, and concurrency support.

### 4. Use of Libraries

- **JavaScript (TypeScript):**
  - Utilizes built-in features like the Internationalization API for number formatting.
  - TypeScript brings static typing to the JavaScript ecosystem.

- **Go:**
  - Uses the `text/template` package from the standard library for string formatting.
  - Simplicity is emphasized in the standard library, with a focus on minimalism.

## Conclusion

Both JavaScript (TypeScript) and Go provide effective solutions for currency formatting, but they have different strengths and use cases. JavaScript, with its extensive ecosystem and focus on web development, incorporates features like the Internationalization API for this task. On the other hand, Go, with its simplicity and efficiency, uses the standard library's `text/template` package for a straightforward and effective approach.

The choice between these languages depends on the specific requirements of your project, the development environment, and your team's expertise. Whether you're building a dynamic web application or a robust backend service, understanding the strengths and characteristics of each language will help you make an informed decision.