Applied Programming/Variables/JavaScript

variables.js

edit
/* This program converts a Fahrenheit temperature to Celsius.

Input:
    Fahrenheit temperature

Output:
    Fahrenheit temperature
    Celsius temperature

Example:
    Enter Fahrenheit temperature: 100
    100° Fahrenheit is 37.77777777777778° Celsius

TODO:
    * All statements are currently global.
    * Functions will be added in a future release.

References:
    * http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
    * http://www.mathsisfun.com/temperature-conversion.html
*/

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

let fahrenheit = input("Enter Fahrenheit temperature: ");

let celsius = (fahrenheit - TEMPERATURE_DIFFERENCE) * TEMPERATURE_RATIO;

output(`${fahrenheit}° Fahrenheit is ${celsius}° Celsius`);

/**
 * Generic input function to get input in HTML, Node, or Rhino environments.
 * 
 * @param {string} text prompt
 * @returns {string} input
 */
function input(text) {
    if (typeof window === 'object') {
        return prompt(text)
    }
    else if (typeof console === 'object') {
        const rls = require('readline-sync');
        let value = rls.question(text);
        return value;
    }
    else {
        output(text);
        let isr = new java.io.InputStreamReader(java.lang.System.in);
        let br = new java.io.BufferedReader(isr);
        let line = br.readLine();
        return line.trim();
    }
}

/**
 * Generic output function to display output in HTML, Node, or Rhino environments.
 * 
 * @param {string} text to display
 */
function output(text) {
    if (typeof document === 'object') {
        document.write(text);
    }
    else if (typeof console === 'object') {
        console.log(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