Skip to main content
Engineering LibreTexts

8.7: JavaScript Examples

  • Page ID
    10716
  • Objects

    // This class converts temperature between Celsius and Fahrenheit.
    // It may be used by assigning a value to either Celsius or Fahrenheit 
    // and then retrieving the other value, or by calling the ToCelsius or
    // ToFahrenheit methods directly.
    
    class Temperature {
        constructor() {
            this._celsius = 0;
            this._fahrenheit = 32;
        }
    
        get celsius() {
            return this._celsius;
        }
    
        set celsius(value) {
            this._celsius = value;
            this._fahrenheit = this.toFahrenheit(value);
        }
    
        get fahrenheit() {
            return this._fahrenheit;
        }
    
        set fahrenheit(value) {
            this._fahrenheit = value;
            this._celsius = this.toCelsius(value);
        }
    
        toCelsius(fahrenheit) {
            return (fahrenheit - 32) * 5 / 9
        }
    
        toFahrenheit(celsius) {
            return celsius * 9 / 5 + 32
        }
    }
    
    // This program creates instances of the Temperature class to convert Celsius 
    // and Fahrenheit temperatures.
    //
    // References:
    //     https://www.mathsisfun.com/temperature-conversion.html
    //     https://en.wikibooks.org/wiki/JavaScript
    
    main()
    
    function main() {
        var temp1 =  new Temperature();
        temp1.celsius = 0
        output("temp1.celsius = " + temp1.celsius);
        output("temp1.fahrenheit = " + temp1.fahrenheit);
        output("");
    
        temp1.celsius = 100;
        output("temp1.celsius = " + temp1.celsius);
        output("temp1.fahrenheit = " + temp1.fahrenheit);
        output("");
        
        var temp2 = new Temperature();
        temp2.fahrenheit = 0
        output("temp2.fahrenheit = " + temp2.fahrenheit);
        output("temp2.celsius = " + temp2.celsius);
        output("");
    
        temp2.fahrenheit = 100;
        output("temp2.fahrenheit = " + temp2.fahrenheit);
        output("temp2.celsius = " + temp2.celsius);
    }
    
    // Checks the JavaScript environment and writes to the console, 
    // the current document, or standard output as appropriate.
    // Reference: http://progopedia.com/example/hello-world/114/ 
    function output(text) {
        if (typeof console === 'object') {
            console.log(text);
        } 
        else if (typeof document === 'object') {
            document.write(text);
        } 
        else {
            print(text);
        }
    }
    

    Output

    temp1.celsius = 0
    temp1.fahrenheit = 32
    
    temp1.celsius = 100
    temp1.fahrenheit = 212
    
    temp2.fahrenheit = 0
    temp2.celsius = -17.77777777777778
    
    temp2.fahrenheit = 100
    temp2.celsius = 37.77777777777778