<h1>Graduate Assignment #1</h1>
<h2>Proving My Understanding</h2>
<p>I've designed a simple calculator that demonstrates an understanding of Week 3-6:
<ul>
<li>Basic data types, variables, objects and mathematical operations</li>
<li>Tests, Lists, and Loops</li>
<li>Functions and Objects</li>
</ul></p>
<p>Please see the comments for explanation!</p>
<hr>
<p>Add, subtract, multiply, or divide two numbers:</p>
<input id="inputField"></input>
<p>The answer is: <span id="result"></span></p>
JavaScript
//design a simple calculator that does one operation on two numbers.
//only acceptable operators are numbers and + - / *
//WEEK 5: FUNCTIONS AS VARIABLES!
var inputField = document.getElementById("inputField");
//onchange means that every time the value in the input box changes, this function will run
//WEEK 6: ASSIGNING A FUNCTION AS A VARIABLE!
inputField.onchange = function() {
document.getElementById("result").innerHTML = calc(inputField.value)
}
function calc(entry) {
//operators array containing the only acceptable operators
//WEEK 4: ARRAYS!
ops = "+-/*";
//WEEK 4: LOOPING!
//for loop iterating over valid operators
for (i = 0; i < ops.length; i++) {
//create new variable for array of the arguments
//and find arguments array values by splitting at the i of operator
var args = entry.split(ops[i]);
//WEEK 4: BASIC CONDITIONALS!
//if the number of arguments values equals 2, then the i of operator
//is equal to the operator in the entry
if (args.length == 2) {
//check to see if the operator in the entry is a "+"
if (ops[i] == "+") {
//WEEK 3: MATHEMATICAL OPERATIONS!
//WEEK 3: TYPE COERCION!
//do the math
//don't forget to check the i of args for numbers
var answer = parseFloat(args[0]) + parseFloat(args[1]);
if (isNaN(answer)) {
var answer = "Beep boop. Something's wrong. Try again!";
return answer;
} else if (!isNaN(answer)) {
return answer;
}
}
//check to see if the operator in the entry is a "-"
else if (ops[i] == "-") {
//do the math
//don't forget to check the i of args for numbers
var answer = parseFloat(args[0]) - parseFloat(args[1]);
if (isNaN(answer)) {
var answer = "Beep boop. Something's wrong. Try again!";
return answer;
} else if (!isNaN(answer)) {
return answer;
}
}
//check to see if the...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.