# Using JavaScript to Avoid a Train Wreck

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

Two trains leaving from different cities head toward each other at different speeds. Train A, traveling 80 kilometers per hour, leaves Philadelphia heading toward New York, 150 kilometers away. At the same time Train B, traveling 120 kph, leaves New York heading toward Philadelphia. When will the two trains meet?

I realize this type of problem may conjure up nightmarish memories of middle school math class. However, stick with me and not only will you be able to solve this problem with ease, but I will also teach you how to write a JavaScript function to solve it for you!

But, before we can write a single line of code we must understand the problem to determine how to solve it.

# 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.

Let’s raise the stakes.

The two trains in this scenario are mistakenly on the same track, heading on a collision course! The first is a commuter train full of passengers and the second is a runaway freight train with a jammed throttle. We need to know how much time there is to prevent disaster. Lives hang in the balance!

From the problem we know several things, some of which are useful. The information relevant to us is the speed of each train and the distance between them. Distance is equal to rate times time and since we know both distance and rate we can solve for time.

`Distance = Rate × Time`

Which can be restated as:

`Time = Distance ÷ Rate`

If we were only concerned with one train traveling to the other city the solution would be obvious. We know the distance (150 km) and the speed of train A (80 kph), so time would simply be 150 km ÷ 80 kph (1 hour, 52 minutes, and 30 seconds). However, our problem involves two moving objects, so we must consider the relative speed of the trains to each other.

Train A is traveling 80 kph, so its relative speed to nearby objects like trees, buildings, and other stationary things is 80 kph. Train B is traveling at 120 kph toward train A, so it appears to be moving much faster to train A than other non-moving objects around. To find the relative speed of the two trains we just add their speeds together, 200 kph in this case.

Knowing relative speed, we can solve for time using the equation above. 150 km ÷ 200 kph = 45 minutes.

We have our answer!

Unfortunately, it took a while to solve. Let’s say that it took ten minutes to explain and solve the problem. That means we actually only have 35 minutes left until train wreck. Precious time lost! What if in the past ten minutes we missed the only opportunity to avoid disaster?

This is where computers come into play.

# 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.

A function definition requires the function keyword, a unique name, a place to receive optional parameters, and a block of instructions to execute.

`function name(parameters) {`

// instructions to execute

}

The name is what must be called to invoke the function. Parameters are optional values that can be provided for the function to work with. The space inside the curly brackets is for code that will run when the function is called.

Since we know how to solve the problem of the two trains we can define a function to solve it for us. We just need to name our function, pass it the relevant information, and translate our formula into code.

Using camelCase, let’s name the function `timeToIntercept`

. The parameters we need to pass to the function are `distance`

, `speedA`

, and `speedB`

.

`function timeToIntercept(distance, speedA, speedB) {`

// instructions to execute

}

The block of instructions will handle computing the solution. Solving the problem takes two steps, so we need to instruct the function how to (1) find the relative speed of the trains and (2) use the formula to solve for time.

We will declare a variable named `relativeSpeed`

and assign it the value of `speedA`

+ `speedB`

. Then we can use the return statement to print out the value of `distance`

÷ `relativeSpeed`

.

`function timeToIntercept(distance, speedA, speedB) {`

var relativeSpeed = speedA + speedB;

return distance / relativeSpeed;

}

Our function is complete! All that is left is to call it and pass in the necessary parameters.

`timeToIntercept(150, 80, 120);`

After the function runs we receive the output:

`0.75`

0.75 hours is the same as 45 minutes.

The function works! The computer can calculate how long until the two trains meet. Now someone just has to prevent the train wreck…

*To test out the code for yourself open the web inspector of your browser and paste both the completed function declaration and the function call into the console panel and press enter.*

# 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.

Next time you find yourself struggling through a middle school math class try defining a function to solve your homework for you.