A Primer on Javascript Functions in Four Steps

Check out the code in Codepen

As a developer who works mainly in server-side languages like PHP, my interest in javascript has always been more on passing variables to functions rather than implementing accordions or slideshows. This primer demonstrates how to use javascript functions with variables in what is hopefully a short but effective set of four examples.

We'll start with a simple function that inserts some text into the page. The function looks like this:

function basicFunction() {
  // set the text
  var theVar = "text generated by js";
  // output the text we just defined to the page by replacing the html content of the element with the ID "basicVar"
  document.getElementById("basicVar").innerHTML = theVar;
}

This works by finding the html element with the ID "basicVar" and replacing the innerHTML with the text from the function. We're hardcoding the text ("text generated by js") in the function itself. We could even skip the first line and write the function like this:

function basicFunction() {
  document.getElementById("basicVar").innerHTML = "text generated by js";
}

The only reason I defined the text as a variable ("theVar") was to get us thinking in terms of variables.

Note that to run these functions you'll need to call them. One way to do this is with the onload attribute:

<body onload="basicFunction(), lessBasicFunction('text from a variable'), evenLessBasicFunction(), advancedFunction()">

Passing a Value to the Function

And now the same idea, but we're passing a value to the function. To do this, when we call the function we pass the value to it like this: lessBasicFunction('text from a variable'):

function lessBasicFunction(theValue) {
  // no need to define the theValue, it's being passed from where the function is called, all we need to do is output it to the page
  document.getElementById("lessBasicVar").innerHTML = theValue;
}

So far so good, but the value "text from a variable" had to be hardcoded into the page when we called the function. That's not very helpful in this case and we might as well have written it like the basicFunction above. But we passed a value to the function as a variable, and that's a start. Let's expand on this idea and create a function that takes two numeric values and outputs them as a total. We'll even put a function inside a function for fun using evenLessBasicFunction and output it to the page.

function evenLessBasicFunction() {
  // let's define two variables
  var var1 = 100;
  var var2 = 400;
  // now let's create a quick function that takes two values and adds them together.
  function addingFunction(value1,value2) {
    return value1 + value2;
  }
  // let's output it to the page
  document.getElementById("evenLessBasicVar").innerHTML = addingFunction(var1,var2);
  // note that we're making this harder than it has to be: we don't have to define our values in var1 and var2, we could just pass them directly to the function when we call it like this: "addingFunction(100,400)" 
}

Now that we've built these three functions, you should see how values can be passed around as variables.

Let's Make it Do Something

Let's add a form so the user can enter something and we can then use that to pass it to the function:

 <input id="formValue" class="the-class" placeholder="type something here">
  <button id="submitButton">enter</button>

And this is our function. It grabs the value of the field and outputs it to the page (to an HTML element with an ID of "advancedVar". It also has conditional logic: there's an if/else statement that checks to see if the value of the input field has been defined and assigns it a value ("empty") if not.

function advancedFunction() {
  // check if there's a value for the form field (which will be blank when the page loads). If not set the value to "empty"
  if ( document.getElementById("formValue").value ) {
    // grab the value from the form, but we'll need to set a listener (below) since it changes when you click the button
    var theVar = document.getElementById("formValue").value;
  }
  else {
    theVar = "empty";
  }
  // now that we have a value for the form field, let's output it to the field
  document.getElementById("advancedVar").innerHTML = theVar;
}

But we'll need a "listener". The form field will be empty on page load, which is why we used the if/else condition to check. If we set a listener it will update the value when someone inputs something and clicks the button:

// set a listener for the "enter" button
document.getElementById("submitButton").addEventListener("click", advancedFunction);

Now we're getting somewhere. We have an interactive page that outputs text dynamically. It uses variables and passes values to functions. It has a nested function, and even uses an if/else condition.

Hopefully this gives you a better understanding of functions and variables. This is just the beginning of what you can do with javascript. Seeing it written out (unlike the "hidden" functionality of jquery and other libraries) exposes the scripting logic and should help you better understand what's happening when your javascript runs.

Check out the code in Codepen

Additional Thoughts

This is all using simple javascript. It's meant to illustrate the logic behind functions and how to pass values to them using variables. There are quicker and better ways to do most of this, like using jquery :). Also, for our form, what if the user hits the "return/enter" key and not the button? There's a listener for that too:

// add a listener for anyone who hits the "return/enter" key instead of the button
document.getElementById("formValue").addEventListener('keypress', function (e) {
  if (e.key === 'Enter') {
    advancedFunction();
  }
});