This article can be used both as a stand-alone reference or as Part 7 of our series on making a t-statistic calculator web app. Please see Part 1 for an overview of this project.
We cannot use HTML to do anything very dynamic. In order to something even as simply as adding two numbers, we will need to write a short program, or script, in another web language, JavaScript. Just like HTML, JavaScript code is interpreted by your web browser to make a website behave in a certain way. One of the easiest ways to start writing JavaScript is to open your web browser's "developer console." In this article, we will write three very short JavaScript programs.
Let's open the "developer console". We can find it in the "Developer Tools" area. You can access these tools by right-clicking and selecting "Inspect."
Once in the Developer Tools area, you can select "Console" from the navigation bar at the top.
If you want a less-cluttered display, you can select a "Separate Window" view:
The Firefox browser has a "multiline code editor" view that is easy to work in:
We can enter our code in the left pane and the result will display in the right pane:
Let's write our first script! In it, we declare a "function" that we will call "addone()". Functions are quite simple. They do any or all of the following:
They can take an input value between the two parentheses right after the function name (i.e., addone(my_input)
). In this case, addone() takes an input value, "my input". When the function is called, my_input is given a value of 7.
They can perform some operation. In this example, the function is adding one to the input value
(i.e., myinput + 1
)
They can return a value. In our example, addone() returns the result of the operation. In the image below, you can see that a value of "8" is returned:
You can make the code run by highlighting it and clicking the "run" icon or simply by ⌘+space.
We can also make a program with no inputs. Here is a function called "sayhi()" that returns the word (or "string" as web developers might say), "Hello!"
Accordingly, notice that there is nothing between the parentheses, neither initially in the function declaration nor later when the function is called.
Finally, we can also make a program with multiple inputs. Here is a function called "addition()" that returns the sum of two numbers:
Of course, an app that simply adds two numbers is not very useful for us. However, this is a good place to start for making a more complicated program. For example, the p-value calculator that we are building in this series will also incorporate a function that takes two inputs -- a t-statistic and the number of degrees of freedom.
Our next step is to make a program that interacts with a webpage, rather than simply running in our browser's developer console. Stay tuned!