Jump to content

JavaScript Programming/Functions/Example Code

From Wikiversity

example.html

[edit | edit source]
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="Cache-Control" content="no-cache">
  <title>Example</title>
  <script defer src="example.js"></script>
</head>

<body>
  <noscript>Enable JavaScript to see web page content.</noscript>

  <p><output id="fahrenheit"></output>° Fahrenheit is <output id="celsius"></output>° Celsius</p>
</body>

</html>

example.js

[edit | edit source]
// This program converts a Fahrenheit temperature to Celsius.
//
// References:
//   https://www.mathsisfun.com/temperature-conversion.html
//   https://en.wikibooks.org/wiki/JavaScript

"use strict";

const TEMPERATURE_DIFFERENCE = 32;
const TEMPERATURE_RATIO = 5 / 9;

main();

function main() {
  let fahrenheit = getFahrenheit();
  let celsius = fahrenheitToCelsius(fahrenheit);
  displayResults(fahrenheit, celsius);
}

function getFahrenheit() {
  let fahrenheit = window.prompt("Enter Fahrenheit temperature:");
  fahrenheit = Number(fahrenheit);
  return fahrenheit;
}

function fahrenheitToCelsius(fahrenheit) {
  let celsius = (fahrenheit - TEMPERATURE_DIFFERENCE) * TEMPERATURE_RATIO;
  return celsius;
}

function displayResults(fahrenheit, celsius) {
  celsius = celsius.toFixed(1);
  document.getElementById("fahrenheit").innerText = fahrenheit;
  document.getElementById("celsius").innerText = celsius;
}