0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Convert Celsius to Fahrenheit

Use the formula fahrenheit = (celsius * 9/5) + 32 in JavaScript like const fahrenheit = (celsius * 9/5) + 32; to convert Celsius to Fahrenheit.
📋

Examples

Input0
Output32
Input25
Output77
Input-40
Output-40
🧠

How to Think About It

To convert Celsius to Fahrenheit, multiply the Celsius value by 9, then divide by 5, and finally add 32. This formula changes the temperature scale from Celsius to Fahrenheit.
📐

Algorithm

1
Get the temperature value in Celsius.
2
Multiply the Celsius value by 9.
3
Divide the result by 5.
4
Add 32 to the result.
5
Return the final value as Fahrenheit.
💻

Code

javascript
function celsiusToFahrenheit(celsius) {
  const fahrenheit = (celsius * 9 / 5) + 32;
  return fahrenheit;
}

console.log(celsiusToFahrenheit(0));
console.log(celsiusToFahrenheit(25));
console.log(celsiusToFahrenheit(-40));
Output
32 77 -40
🔍

Dry Run

Let's trace converting 25 Celsius to Fahrenheit through the code

1

Input Celsius

celsius = 25

2

Multiply by 9

25 * 9 = 225

3

Divide by 5

225 / 5 = 45

4

Add 32

45 + 32 = 77

5

Return Fahrenheit

fahrenheit = 77

StepOperationResult
1Input Celsius25
2Multiply by 9225
3Divide by 545
4Add 3277
5Return Fahrenheit77
💡

Why This Works

Step 1: Multiply Celsius by 9

Multiplying by 9 scales the Celsius temperature to the Fahrenheit scale proportionally.

Step 2: Divide by 5

Dividing by 5 adjusts the scale difference between Celsius and Fahrenheit degrees.

Step 3: Add 32

Adding 32 shifts the zero point from Celsius to Fahrenheit, aligning freezing points.

🔄

Alternative Approaches

Arrow function
javascript
const celsiusToFahrenheit = celsius => (celsius * 9 / 5) + 32;
console.log(celsiusToFahrenheit(100));
Shorter syntax using arrow function, good for concise code.
Using Math.round for integer output
javascript
function celsiusToFahrenheit(celsius) {
  return Math.round((celsius * 9 / 5) + 32);
}
console.log(celsiusToFahrenheit(36.6));
Rounds the result to nearest integer, useful when decimals are not needed.

Complexity: O(1) time, O(1) space

Time Complexity

The calculation uses a fixed number of arithmetic operations, so it runs in constant time.

Space Complexity

Only a few variables are used, so the space needed is constant.

Which Approach is Fastest?

All approaches perform the same constant-time calculation; differences are mainly in syntax and readability.

ApproachTimeSpaceBest For
Standard functionO(1)O(1)Clear and easy to understand
Arrow functionO(1)O(1)Concise syntax for simple functions
Rounded outputO(1)O(1)When integer results are preferred
💡
Remember to use parentheses to ensure correct order of operations in the formula.
⚠️
Forgetting to add 32 after multiplying and dividing causes incorrect Fahrenheit values.