Using JavaScript to Avoid a Train Wreck

Demonstrating the value of functions by determining the timing of a train wreck

Understanding the Problem

In my wholesome homeschool mathematics curriculum the trains were always happy little locomotives, pulling passenger cars, traveling on parallel tracks whose engineers simply wanted to know when they would get to wave to each other.

Distance = Rate × Time
Time = Distance ÷ Rate

Defining a Function

In computing, a function is a reusable block of code designed to execute a task when called. Many programming languages use functions, but we are going to focus on JavaScript as its syntax is easy to understand and you can run the code for yourself in an internet browser.

function name(parameters) {
// instructions to execute
}
function timeToIntercept(distance, speedA, speedB) {
// instructions to execute
}
function timeToIntercept(distance, speedA, speedB) {
var relativeSpeed = speedA + speedB;
return distance / relativeSpeed;
}
timeToIntercept(150, 80, 120);
0.75

The Value of Programmatic Functions

Once defined a function can be called over and over again. The ability to pass in parameters means the same function can be used to solve this type of problem for any given variables. Best of all, the computer is able to solve the problem in a matter of milliseconds, an insignificant fraction of the time it takes you to even call the function with your fumbling human fingers.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store