You deserve a Coke

A glass filled with Coca-Cola splashing with a dropped ice-cube

Functions are a core part of JavaScript; they’re used everywhere. Thankfully, basic functions are also pretty straightforward.

Functions Automate Tasks

Let’s imagine you’re coming home after a hard day’s work, and that at the end of the day, there’s nothing you like better than a glass of ice-cold lemonade. Good news: in the magical future world of home automation, you won’t have to make it yourself; your friendly household robot can prepare your drink for you. All we have to do is to write a function to make that happen.

To start, let’s write it in pseudo-code: a “sketch” that won’t actually work in a browser, but will give us an idea of what we’re after:

door.open {
    makeLemonade();
}

In this scenario, the door is an object, open is an event, and makeLemonade is a function. We haven’t written that function yet, so our home automation system has no idea what to do when it encounters our call to makeLemonade(). Let’s change that by adding the following:

function makeLemonade() {
	squeezeLemons;
	addSugar;
	…
}

Pretty straightforward, right? The function breaks down the task of making lemonade into individual statements in a code block between opening and closing curly braces. When we want those statements to be executed, we call on the function by name.

Let’s write some actual code now. Sadly, we don’t yet have a lemonade-making household robot; instead, we’ll write some JavaScript to change an image and some text on a web page.

First, let’s add default text and an image to the page, just in case the JavaScript doesn’t execute for any reason, using the principles of graceful degradation:

<section id="welcomebeverage">
    <h1>You deserve a Coke</h1>
    <img src="coke.jpg" alt="A glass filled with Coca-Cola 
	splashing with a dropped ice-cube">
</section>

We’ll declare our function in a script at the end of the page (positioning the script in this location will effectively act as a “document load / door open” event).

var welcome = document.getElementById("welcomebeverage"),
welcomeMsg = welcome.querySelector("h1"),
welcomeImg = welcome.querySelector("img");
function makeLemonade() {
	welcomeMsg.innerHTML = "You deserve a frosty lemonade.";
	welcomeImg.src = "lemonade.jpg";
}
makeLemonade();

Assuming we have coke.jpg and lemonade.jpg beside our page, the result will look something like this:

You deserve a lemonade

This is good, but there’s really nothing here that couldn’t be made without a function, as the code is called just once. Let’s expand on that: say you wanted the function to serve you a cappuccino in the morning and a lemonade in the afternoon/evening, with a Coke at all other times. To do this, we’ll abstract our code to include other beverages:

function makeBeverage(drink) {
	var welcome = document.getElementById("welcomebeverage");
	var welcomeMsg = welcome.querySelector("h1");
	var welcomeImg = welcome.querySelector("img");
	var beverages = ["Coke", "cappuccino", "lemonade"];
	welcomeMsg.innerHTML="Hey - you deserve a "+beverages[drink];
	welcomeImg.src=beverages[drink]+".jpg";
}
var currentTime = new Date();
var timePeriod = Math.round(currentTime.getHours()/12);
makeBeverage(timePeriod);

The JavaScript function has been expanded to include a parameter. This parameter is referenced inside the function as a variable, and usually contributes to changing its output. In this case, we’re sending makeBeverage an argument: the current time on the user’s device. This value is measured in 24-hour time, divided by 12; so it’s between midnight and 6am, the value will be 0; 6am to noon, 1, and so on.

Functions are sent arguments; they receive parameters.

Our function receives this information - the 0, 1 or 2 value - which is referenced as a variable within the scope of the function, using the parameter name between the parentheses. In this case, the value of 0, 1 or 2 is placed inside a parameter called drink, which is used to look inside a beverages array. The appropriate “slot” in the array, based on this value, is then used to complete the welcoming message and image via concatenation.

As a result, the offered beverage will differ between three options, depending on the time of day. But this function still runs only once. To change that, we’ll use setInterval to call the function every hour.

Functions Do Anything You Want Done More Than Once

We’ll add one line to the end of the script:

setInterval( function() { makeBeverage(timePeriod); }, 1000*60*60 );

We can call a function as many times as we want, and from anywhere in a script. This line uses an anonymous function to set a callback to makeBeverage every hour. The makeBeverage() line immediately before it remains in place, as we want the function to run immediately when the page is loaded, and again every hour after that.

Conclusion

There’s much more to functions, including functions returning values, function expressions, and immediately invoked functions. I’ll cover those in future articles; for now, experiment with the example on CodePen, with the knowledge that you’ve just learned of the most powerful features of JavaScript and most other coding languages.

Photographs by Michael Fludkov, themysteryman and Bryan Pocius, licensed under Creative Commons.

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.
Check out the CodePen demo for this article at https://codepen.io/dudleystorey/pen/XbjMbr