Calculators

There has been a lot going. One of those things has been coding. I have been trying in my spare time to update my science website with new calculators for the students to use in their studies. These calculators are meant to provide a resource that allows them to check answers or even answer randomly-generated questions.

I had created a heat equation calculator last year for my honors class. Unfortunately, I hadn’t finished it before the unit was complete, but this year the students were able to make use of it. I wrote it in C# when I was first getting into a contemporary computer language. Kevin helped me to translate it over using bridge.net to run on my website through JavaScript. Part of me wants to rewrite it in pure JS to apply my coding skills and see where I’ve grown. But I have other pressing things to do.

I created a density calculator too. It’s not the ideal for what I wanted, but it is a start. Put in any two variables into the equation d = m/V and the calculator will find the missing variable. It will also show if the object will float or sink in various materials, and it also shows a prediciton of where the object would float in water. 

These are all part of my normal curriculum, but now I have a page set up where the students can practice. I still need some time to work on the image scale and the layout, but at least the info is there. I’m trying to balance fitting everything on a computer scfreen, but I’m also aware that some students may use their smart phones. I know it is possible to have a stylesheet set up to accommodate media type, but I haven’t delved down that path yet.

I was also able to figure out a factor label calculator, which I hadn’t been able to do in C#. I didn’t create it the way I wanted to… The applet doesn’t “think” through the answer like I was hoping. Instead, I hard-coded a set of possible paths and let it work itself out from there. It works, but it isn’t as easily expandable as I wanted it.

For later this year, I wanted to have that “thinking” model in place for when I get my honors classes up to multi-step calculations. I wanted the applet to be able to generate workable questions and show solutions. I need to master the concepts of breadth-first searches and depth-first searches to see if I can get to the answer. But I need more work with data structures to get there.

The next calculator I need to create is for the Ideal Gas Law. There are three types of questions that can be asked and I want to be able to provide that calculator as another resource for the students.

Lastly, I also created a quiz program, which I dubbed, “The Quizzler”. It currently only has questions for density and phases of matter, but I’m hoping to add to the question libarary through the year and deepen its use. The phases questions are all pre-written, but the density ones include randomized calculations for endless questions. I can use the structure of it later for when we’re into physics and we have a lot of similiar-format equations, like F = m a, W = m g, p = m v, and so on.

So, go on and practice some science!

For most of the links, the calculator is located at the bottom of the page, after the notes.

 

JavaScript in Short

img_6773September is going to be an interesting challenge. I am developing a new course and have been prepping for it all summer by familiarizing myself with as much code as I can. I feel confident that I can handle JavaScript, HTML, and CSS in the coming school year. Presenting it and teaching my students to debug it all will be the next challenge. In the meantime, here is a very brief overview.

Punctuation

JavaScript is case-sensitive, like most passwords. A capital “J” is different than a lowercase “j”. Keywords, which instruct the computer what to do, are all lowercase. Developer-created variables and functions have to have a single-word name with no spaces. So we use camelCase to show different words in a chain. It’s like a hashtag with each word starting with a capital. It makes it much easier to read: carStartingPosition, ShowTextOnScreen, testScore2. A few other special characters can be used, but they’re frowned upon. Stick with standard letters, numbers if needed (but not the first character), and underscores. There’s more to the rules of convention here, like variables and properites should begin with a lowercase letter, while constructor functions begin with an uppercase letter, and constants are all caps with words separated by underscores. The main concepts are not to use spaces and to make it easy to read.

Each statement should end with a semicolon. If you don’t put them in, the browser will do its best to parse your code to make sense of it and figure our where each statement ends. It is a better practice to just tell the computer where you want each statement to end. Consider this:

thebrowserwillreadthroughyourcodeontheflywhileitisrunningyourwebsitesometimesitwillstumbletryingtodecipher ambiguousstatementsyesitwilldoareallygoodjobmostofthetimebutwhychanceitjustputpunctuationintheretohelp

Consider that statement. Could you read it? Was it easy or did it take a minute to parse the words and figure out what it was saying?

JavaScript can understand ‘single quotes’ or “double quotes”. Either is fine, but be consistent. I stick with double quotes except in special circumstances.

Comments

Insert comments in your code to explain what your code is meant to do. You can also comment out lines of code to skip over them while you debug your work. There are two ways to add a comment. Use a double slash // to comment out a single line of code. Wrap a comment block with /*     */ to hide several lines of code.

Variables

These are used to store values in a program. They allow for values to change and to be tested against repetitive conditions. If you’re going to make a cold cut sandwich, the variables would be things like the type of bread, the type of cold cuts, the number of slices, etc. The sandwich itself is made through a repetitive process; bread slice, spread, cold cuts, bread slice. You can swap out the actual parts, but the underlying process is the same. That’s one of the powers of variables.

There are three types of variables (for simplicity I’m separating out other types into their own categories): numbers, strings, and booleans. A number is what you’d expect: 3.14, 42, -12. A string is any collection of characters, like words, set inside quotes: “hello!”, “This is a test.”, “32”. (Yes, you can treat a number like a string, which can cause different behaviors.) A boolean is a flag that is either set to true or false.

Variables are declared using the var keyword. You can just declare a variable, or you can assign its value when you declare it. var x; var y = 33; var myName = “Steve”;

Input/Output

In many programs, you want the user to input some information and then react to it. You also want to provide feedback to the user when a task is done, or with updates along the way. In JavaScript alone, you’re limited to the console window or alert/prompt boxes. More commonly, the input/output is passed to a webpage by updating HTML. To write to the console, use the log method of the console: console.log(“Hello there”); It is possible to pass variables in there too: console.log(myName);

You can also pop up a dialogue box with information using the alert() function: alert(“Hello again!”); This also accepts variables: alert(myName);

To get text input from a user, use the prompt command. Typically, you assign this to a variable so you can run tests on the answer: var yourAnswer = prompt(“What is your favorite color?”); You can also supply a default answer: var yourOtherAnswer = prompt(“What is your name?”, “Steve”);

There are different methods for HTML and they all look scary at first. Top priority is to have a unique id for each element you want to access, then you call the element through the HTML document. You can do this to retrieve info or to update it. 

To get information from a user from a tag that has “answer” for its id: var yourAnswer = document.getElementById(“answer”).value;

To post information to a tag with an id of “response”: document.getElementById(“response”).innerHTML = “That’s a good answer.”;

Operators

There are several operators. Math operators are great for numbers (+, -, *, /, %). Modulo (%) returns the remainder after division, so 20 % 3 is equal to 2, because 3 goes in 6 times to get 18 and 2 is leftover. 

Operations on variables don’t look like regular algebra. If you have a variable (x) and you want to increase its value by five (5), you use: x = x + 5; In algebra, this wouldn’t make sense. If you tried to solve for x, you’d get 0 = 5 which is crazy. Instead, the computer evaluates the express on the right side of the equals sign (x + 5 in this case) and when it has the answer, it then replaces the value on the left side (x in this case) with the answer. 

++ increases the value of a number by 1 and — decreases the value by 1. Example: numberOfCookies++;

Strings are concatenated (joined together) with use of the + sign. “Hi” + “there” would give “Hithere”.

The dot operator is used to access properties of objects. To find the size of an array, for instance, use myArray.length; 

Functions

A function is a set of code used to complete a single or small task. It can be called as needed over and over. It is possible to pass parameters into a function and it is possible to return values from the function. Declare a function with the keyword function.

function CalculateArea(w, h)

{

  return w * h;

}

Call the function: CalculateArea(4, 7); //This would return a value of 28. The value can also be stored in a variable: var area = CalculateArea(10, 22); 

Functions do not need to return any variables. They can just carry out actions.

function SayHello(name)

{

  console.log(“Hello, ” + name + “!”);

}

They also don’t need any parameters, so they’re very flexible based on your needs.

function sayGoodbye()

{

  alert(“Bye-bye!”);

}

 Conditional: if/else

Computers need ways of making decisons. An ‘if’ statement tests for a condition. If it is true, then a certain code block will run. You can also set up an else statement that activates if the condition is false. Conditons can be comparisons, such if a number is greater than another number, or it can test if a boolean is true.

if (x > 5)

{

  console.log(“It’s greater than 5.”);

}

else

{

  console.log(“It is not greater than 5.”);

}

The else statement is not required but it is a good way for controlling code. It is also possible to nest several if statements together to make a logic chain. When one part of the chain is activated, the program steps out of the conditionals and runs the rest of the code after the logic chain.

if (y < 0)

{

  console.log(“y is negative”);

{

else if (y > 0)

{

  console.log(“y is positive”);

}

else

{

  console.log(“y is equal to zero”);

}

It is also possible to test for two (or more) conditions at once. Let’s say you want to decide if you should wear a jacket. You’ll need one if it is cold or if it is raining. Use the OR operator || if only one condition needs to be true. If all conditions need to be true then use the AND operator &&.

if (temp < 50 || itIsRaining)

{

  PutOn(“jacket”);

}

 

if (temp > 70 && itIsSunny)

{

  Remove(“jacket”);

}

Conditional: switch

When you have a lot of conditions to test against a single variable, you could use a whole set of if/else statements, but a switch statement is a cleaner way to go. A switch can be used for strings or numbers. Set up all the cases to test and it is prudent to also include a default at the end. Each case needs a break statement. If two cases give the same result, it is possible to have one case drop through to the next.
 
switch (day)
{
  case “Monday”:
    console.log(“Wake up early!”);
    break;
  case “Saturday”: //this case will fall through to “Sunday”
  case “Sunday”:
    console.log(“You can sleep in!”);
    break;
  default:
    console.log(“Check your calendar.”);
}

Comparisons

When comparing two values, it is possible to test if two values are equal. To do so, use a double equal == to see if the values are the same. There are some things going on behind the scene so you may get some unexpected results. For example, if you compare a number and a string, JavaScript automatically tries to turn the string into a number for you. Likewise, when comparing a boolean, it converts true to 1 and false to 0. While this may make some comparisons seem easier, unless you’re aware of what the rules are, you’ll get some unexpected results. You’re better off with cleaner code anyway.

JavaScript also allows you to test if two values are the same number and the same type. For this, use a triple equals sign ===. Because variables in JavaScript are dynamic, it is always a good idea to use the triple equals for all comparisons. It is otherwise possible for two different variables to test as equal.

“2” == 2 //true because the values are the same

“2” === 2 //false because the first value is a string and the second is a number

You can also test for “less than or equal to” using <= or “greater than or equal to” >=

You may also need to test if something is not true. For this, use ! at the front of the comparison operator, such as !== for “not strictly equal to”. Examples: x !== 7; !snowingOutside;

Loops

A loop is useful when you need to repeat a block of code a certain number of times. It wouldn’t be good to write the same code over and over. It is better to use a loop. Let’s say you needed to fix a part of the code, you would have to change all the different lines you wrote in. But if you wrote it as a loop, then you only have to change the code once, inside the loop.

There are two types of loops, a for loop and a while loop. Use a for loop when you know how many times you need to run the code. Use a while loop when you don’t know how many times to run the loop.

while (itIsRaining)

{

  WipeOffWindshield();

  isItRaining = CheckForRain(); //this checks to see if it is still raining

}

There is a variation of the while loop called a do while loop. The difference is that the code in the block always runs at least once, whereas in a while loop, it is possible for the loop to be skipped entirely if the condition started as true.

do 

{

  WashYourHands();

}

while (handsAreDirty);

A for loop is set up differently. It has three main parts: an initializer that sets a starting counter (var i = 0), a condition thats keeps the loop running as long as that is true (i < 10),  and the incrementer for the loop (i++). You can use any variable name, but “i” is often used as an abbreviation for “iteration”  The incrementer can go up or down and it can do than count by 1. To count by three, use i = i + 3 instead of i++.

for (var i = 0; i < 10; i++)

{

  console.log(i);

}

A loop can also be controlled from within using the keywords break; and continue;  A break; command will exit the loop and move on outside the loop. A continue; command is used to jump to the top of the loop and keep going without finishing the code in the loop.

Arrays

An array is a variable that holds a list of information. Think of a shopping list or a set of test scores. Arrays are set up with square brackets []. Individual items are separated by commas. Elements in an array can be added or removed and so programs can be flexible. Also, it is possible to access individual iitems in an array using the index of items on the list. Index numbers start at zero.

var scores = [75, 88, 95, 82];

var foodList = [“lettuce”, “loaf of bread”, “cheese”];

Access items in the array using the index. Remember, indexes start at zero. scores[0] would be 75 and foodList[2] would be “cheese”. You can set items using the index number too. foodList[3] = “milk”;

You can also use array methods to alter the list. Use the name of the array, a dot, and the name of the method you want to use.

scores.push(83); //adds 83 to the end of the array list

scores.pop(); //removes the last item from the list, which can be saved to a variable: var last = scores.pop();

scores.shift(); //removes the first element and shifts the other elements an be saved to a variable

scores.unshift(91); //inserts a new value at the start of the list

scores.sort(); //alphabetizes or sorts the items on the list

scores.splice(2, 1, 77, 78) //at index 2, remove 1 item, then insert 77 and 78

scores.concat(moreScores) //add the contents of one array to another; this produces a new array

Objects

An object is like a super-variable. It holds several pieces of information related to a single object. It can hold variables, arrays, and functions, etc. Each variable is considered a property and is accessed using a dot operator. Properties should be set up when the object is created, but JavaScript lets you create properties on the fly. As convenient as that can be, it can lead to debugging problems and inconsistency in the code.

To understand an object, think of a car. A car has a make and model, a year, a color, cruise control, etc.

var myCar = {

    make: “Subaru”,

    year: 2015,

    cruiseControl: true,

    drive: function() { alert(“Zoom!”); },

    registrationDue: this.year + 1;

};

You access the information using the dot modifiers: myCar.year; Properties can also be reassigned in this way: myCar.cruiseControl = false; You shouldn’t, but you can make new properties by assigning them: myCar.color = “blue”;

If your object has functions inside, they’re called “methods” to distinguish them as belonging to an object. They’re just regular functions, but you call them with the dot operator. myCar.drive(); There’s a lot more complexity possible too. There is the “this” keyword that lets the object reference itself so it is possible to perform operations or methods within the object on the object itself. It is advanced stuff and takes some getting used to.

Scope

It is possible to set up variables that only exist in small, temporary locations. This is called scope and it is very useful. Whenever possible, sll variables should be the local scope. The global scope should be avoided whenever possible, but sometimes it can’t be helped. As the name implies, a variable in a global scope can be used anywhere in your program by any function or operation. This may work for some things, but let’s say you have a counter variable, it could accidentslly be changed by another counter variable that has the same name elsewhere. The only way to change scope in JavaScript is to use functions. A variable that is declared inside a function is only visible within that function. Note: there is an exception to this rule through the use of closures, but that’s more advanced stuff. 

var numberOfSandwiches = 5; //this is a global variable

function makeASandwich()

{

  var slicesOfBread = numberOfSandwiches * 2;

  console.log(numberOfSandwiches); // shows: 5

  console.log(slicesOfBread); // shows: 10

}

  console.log(numberOfSandwiches); // shows: 5

  console.log(slicesOfBread); // shows: undefined <– slicesOfBread was defined inside the function so it doesn’t exist outside of it

Conclusion

There are many other nuances to cover but this guide is meant only to be reference or a refresher. You can’t really learn to code until you try to make your own programs. Typing in someone else’s is s good place to start, ut you have to try creating your own inorder to understand what is happening. Even with what I know and understand, there are times where I will overlook a nuance and something won’t behave as expected. The best practice you can get comes from debugging your code and figuring out why the unexpected happened and figuring out what you have to do to fix it. Ask for help, sure, but you’ll learn better if you try to fix it yourself. Good luck.

Battles in Kallisor

It’s not easy fighting monsters. And in this case, we’re talking about code bugs.

I’ve been working on a JavaScript coding curriculum for my seventh graders. Because of limited time with them, I really hit them hard with a lot of code concepts and just moved on. Most are picking up the basics, which has been great. Some excel because they’re more interested or they’ve done some JavaScript before, so while they’re working on some of my code samples, it allows me to help the ones who are struggling.

I’ve had a good time with it, even though it’s been a ton of work. I mentioned last time that I was working on a WinForms RPG based on Dariak’s childhood, complete with quests and so forth. That was all being done in C# and making use of the easy-to-use UI of Windows Forms. It’s a lot of drag-and-drop formatting and that makes the visual setup so much easier than making a nice-looking HTML page.

But we have Chrome Books at school so there’s no Windows. Worse than that, there’s no Visual Studio, which is an amazing IDE (think: word processor for coding). To work with my students, the coding all has to be done via the web. I found this awesome coding site, repl.it, which has IDEs for multiple languages. It really helps with setting up and testing code.

The problem with JavaScript is that it’s a behind-the-scenes language. It runs all the logic, but it doesn’t display things well at all. That requires HTML and CSS. Altogether, that’s three languages needed to present one thing. It’s a bit overwhelming. I’m only showing my students JavaScript for now because of time.

But I want to show them that it can also hook up to the web, so I made a miniature battle program that is similar to the one I was making in the larger game venture. There are no magic spells or special skills and the only item you have access to is a healing herb. I also need to work on the battle algorithm (a lot). But for what I want the students to see and play with for now, this is perfect.

If you want to check out the JavaScript only version, you can look at it here. And if you want to see the 2.0 HTML version, this is it. You do not need to log in to try it. You can X out the login screen. To run the code, find the triangular button in the left window pane. You can also drag the window divider to make a window bigger or smaller.

Please let me know if you try it and you find any bugs. I need to squash those, just as Dariak is squashing rodia!