Skip to content

Instantly share code, notes, and snippets.

@Pythonian
Created June 23, 2022 13:47

Revisions

  1. Pythonian created this gist Jun 23, 2022.
    42 changes: 42 additions & 0 deletions calculatorjs.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Javascript calculator</title>
    </head>
    <body>
    <script>
    // holds the kind of arithmetic operation to be performed
    const operator = prompt("Which arithmetic operation do you wish to perform (+, -, * or /)? ");

    // prompt the numbers for the computation from user
    const number1 = parseInt(prompt("First number: "));
    const number2 = parseInt(prompt("Second number: "));

    // variable to hold the result of the computation
    let result;

    if (operator == "+") {
    // addition operator
    result = number1 + number2;
    } else if (operator == "-") {
    // subtraction operator
    result = number1 - number2;
    } else if (operator == "*") {
    // multiplication operator
    result = number1 * number2;
    } else if (operator == "/") {
    // division operator
    result = number1 / number2;
    }
    else {
    // if the operator entered is not among the options
    alert("Invalid operator");
    }

    // display the result to HTML
    document.write("Computation: " + number1 + "" + operator + "" + number2 + " = " + result);
    </script>
    </body>
    </html>