Computer Programming/Functions/JavaScript

From Wikiversity
Jump to navigation Jump to search

subroutines.js[edit]

// This program asks the user for a Fahrenheit temperature,
// converts the given temperature to Celsius,
// and displays the results.
//
// References:
//   https://www.mathsisfun.com/temperature-conversion.html
//   https://en.wikibooks.org/wiki/JavaScript

main();

function main() {
  var f = getF();
  var c = calculateC(f);
  displayResult(f, c);
}

function getF() {
  var f = input("Enter Fahrenheit temperature:");
  return f;
}

function calculateC(f) {
  var c = (f - 32) * 5 / 9;
  return c;
}

function displayResult(f, c) {
  output(f + "° Fahrenheit is " + c + "° Celsius");
}

function input(text) {
  if (typeof console === "object") {
    return prompt(text);
  } 
  else {
    output(text);
    var isr = new java.io.InputStreamReader(java.lang.System.in);
    var br = new java.io.BufferedReader(isr);
    var line = br.readLine();
    return line.trim();
  }
}

function output(text) {
  if (typeof console === "object") {
    console.log(text);
  } 
  else if (typeof document === "object") {
    document.write(text);
  } 
  else {
    print(text);
  }
}

Try It[edit]

Copy and paste the code above into one of the following free online development environments or use your own JavaScript compiler / interpreter / IDE.

See Also[edit]