JavaScript: converting between Fahrenheit and Celsius degrees

JavaScript: converting between Fahrenheit and Celsius degrees

In this article, we'll explore how to create a function for bidirectional conversion between Fahrenheit and Celsius in JavaScript.

Converting between Fahrenheit and Celsius degrees is a common operation when working with temperatures. Implementing a function that allows you to convert from one system to another in JavaScript can be very useful in many applications, such as weather apps, online calculators or environmental monitoring dashboards. In this article, we'll explore how to create a function for bidirectional conversion between Fahrenheit and Celsius in JavaScript.

Basic concepts

Before starting the implementation, it is essential to understand the conversion formula between degrees Fahrenheit (°F) and Celsius (°C):

Fahrenheit to Celsius:


°C = (°F - 32) * 5/9

Celsius to Fahrenheit:


°F = (°C * 9/5) + 32

Implementation

Here's how we might implement conversion functions in JavaScript:


// Function for converting Fahrenheit to Celsius
function fahrenheitToCelsius(fahrenheit) {
     return (fahrenheit - 32) * 5/9;
}

// Function for converting Celsius to Fahrenheit
function celsiusToFahrenheit(celsius) {
     return (celsus * 9/5) + 32;
}

The two functions fahrenheitToCelsius and celsiusToFahrenheit take respectively a temperature in degrees Fahrenheit or Celsius as an argument and return the equivalent temperature in the other system.

Examples:


// Convert Fahrenheit to Celsius
const fahrenheitTemp = 68;
const celsiusTemp = fahrenheitToCelsius(fahrenheitTemp);
console.log(`${fahrenheitTemp}°F equals ${celsiusTemp.toFixed()}°C`);

// Celsius to Fahrenheit conversion
const celsiusTemp2 = 25;
const fahrenheitTemp2 = celsiusToFahrenheit(celsiusTemp2);
console.log(`${celsiusTemp2}°C correspond to ${fahrenheitTemp2.toFixed()}°F`);

In the examples above, we used the toFixed() method to round off the conversion result. This makes the output more readable without overloading it with unnecessary decimal places.

Conclusions

Converting between Fahrenheit and Celsius degrees is a common operation and can be implemented easily using the appropriate conversion formulas. Creating functions dedicated to this conversion in JavaScript allows you to make the code more readable, modular and easier to maintain. These functions could be integrated into more complex applications involving temperature monitoring, online calculators or other situations where it is necessary to convert between the two measurement systems.