Jump to content

Programming Fundamentals/Variables/JavaScript

From Wikiversity

variables.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

var fahrenheit = input("Enter Fahrenheit temperature:");
var celsius = (fahrenheit - 32) * 5 / 9;
output(fahrenheit + "° Fahrenheit is " + celsius + "° Celsius");

function input(text) {
  if (typeof window === 'object') {
    return prompt(text)
  }
  else if (typeof console === 'object') {
    const rls = require('readline-sync');
    var value = rls.question(text);
    return value;
  }
  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 document === 'object') {
    document.write(text);
  } 
  else if (typeof console === 'object') {
    console.log(text);
  } 
  else {
    print(text);
  }
}

Try It

[edit | edit source]

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 | edit source]