JavaScript for WordPress Developers: Learning the Basics

WPTavern: 18 WordPress Plugins Updated Due to Summer of Pwnage Findings, 40+ Vulnerabilities Still in Reporting Stage
July 20, 2016
Free Divi Download: The Divi Header UI Kit
July 20, 2016
Show all

JavaScript was developed over 20 years ago at Netscape and for a while in the mid-late 1990s it was considered a roadblock to a standardized web. Look how far we’ve come since!

JavaScript is now used on 93.6% of all websites in the world. Automattic even recently developed a desktop client for, written in 100% JavaScript. Whole sites and apps can be built with JavaScript-only tools like Angular and React.

The web is moving ever-faster toward a more JavaScript-filled life. WordPress won’t be ditching good ol’ PHP any time soon, but there is a significant shift in focus nowadays towards JavaScript and developers have to keep up.

So in this four-past series, I’ll introduce you to JavaScript for WordPress developers and open your eyes to the world of JavaScript and what it means for working with WordPress.

Throughout this series, you’ll learn the basics but I’ll presume you already have a working knowledge of HTML and CSS. If you need help with these building blocks, take a look at our series about WordPress Development for Beginners.

Getting Started

The good news about JavaScript is that a large portion of it is client-side and is built right into your browser. This means that you can get started without any special setup. All you need is an HTML file.

A Simple Boilerplate

Let’s create that HTML file now! All we need is a basic HTML 5 frame and a script tag within it. Here’s how it should look:

.gist table { margin-bottom: 0; }

JavaScript can be linked to our document from external sources or can be placed inline, just like CSS.

Let’s settle for the inline method for now. We’ll look at how to include JavaScript from files later in this article.

When writing JavaScript inline you should wrap the code within script tags as I have done in the example above.

The first thing we’ll learn is how to display some data so we can observe what we’re doing. Let’s get started.


An alert box is an annoying popup containing a message and a button that allows you to close the popup. It has a few legitimate uses but may be familiar mostly from spam ads and other trickery.

Alert Box
Alert Box

Alerting can sometimes be a quick way to debug something in your code. There are many better methods but for the moment alerting is one of the quickest solutions and is just fine for our purposes.

Simply type alert('Write any message here') within the script tags and reload the page.

Console Logging

A more flexible way of displaying data is to log it in the console. If you’ve been using HTML, CSS and PHP, chances are that you’ve seen the console. It can be found in the developer tools section of every browser.

Chrome's Javascript Console
Chrome’s JavaScript console

I’ve mistyped the code from before using alerts('message'). Since alerts is not a JavaScript function the console gave me the above error. JavaScript will log errors and other messages in the console for you, but you can utilize it for your own needs.

Use console.log('Write anything here') to a log text to the console. As you’ll see later you can log arrays and objects as well, which makes this a lot more flexible than alerting.

Console Logging Data
Console Logging Data

Writing Into the Document

JavaScript can also place content within the HTML structure using document.write. I don’t think I’ve ever used this method though since there are better ways of modifying HTML from within your JavaScript code, but we’ll use it in a couple of examples to avoid unnecessary complexity. Here’s how it works:

.gist table { margin-bottom: 0; }

The Building Blocks of JavaScript

JavaScript, like many other languages, is based on concepts like variables, functions and objects. In this article, we’re focussing on variables, functions and how to write JavaScript. I recommend taking as much time as you need to understand these concepts because they are used in every programming language, not just JavaScript!

Adding JavaScript to Our Page

I’ve already shown you how to write JavaScript inline, but there are other ways and other considerations. You can add JavaScript to the HTML section or within the .

Most JavaScript code is only needed once the page has loaded. Due to this, it is customary to put as much of your code just before closing section – it makes pages load a lot faster.

It is also a good idea to separate your JavaScript code from your page, just like we do with CSS. You can write your code in one or more external files and then link them to the page. This can also be done in the head or body sections using a script tag with an src attribute.

.gist table { margin-bottom: 0; }


Variables allow you to store a value for use later. A large part of programming is writing reusable code, variables are concepts that make this possible. Assume you’re creating a welcome page for logged in users.

Let’s output a few random bits of text which might be used on this page:

.gist table { margin-bottom: 0; }

As you can see my name is used quite a lot. We can create a variable and assign it a value (my name) and use that variable later.

.gist table { margin-bottom: 0; }

In a simple case like this, the value is not immediately obvious, it’s just a line more. In a real life situation this could not only save you scores of lines but is useful far beyond substitution.

In a real application the value for the name variable would be retrieved from the database. If John logs in he would see “Hello John” whereas Jane would see “Hello Jane.”

Before we move on, let’s memorize some of the syntax. When creating a variable you write the var keyword, followed by the name you want to refer to the variable by, followed by an equals sign and the value of the variable.

If a value is a string you need to quote it. If it is a number you should write it without quotes. Finally, you end the line with a semicolon.

When using a variable within string we use concatenation. A plus sign will concatenate (add) a variable to the string. The general format is: "some string" + variable + "other string".

Before we move on I want to mention something about the var keyword and the semicolon. Technically the var keyword is not necessary to define a variable. If you omit it you will create a global variable which can be accessed from anywhere. This is usually not a good idea because you’ll end up with tangled code. For now, add var before all your variables.

The semicolon is also not required. It is only required if you write two statements on the same line.

.gist table { margin-bottom: 0; }

I prefer to add semicolons after every line to avoid confusion and keep a standard syntax. It will also come in handy when learning PHP where you must use the semicolon.


WP Academy – WordPress Wisdom, Bitesized.

Structured e-learning to expand your WordPress and general business horizons. Learn from people like our very own CEO James Farmer with more than a decade’s experience running a WordPress Business!.



Functions are another way to write reusable code. Let’s use an analogy to understand why functions exist. Let’s say you really enjoyed the The Utimate Guide to WordPress Multisite and regularly refer to it. You can’t remember the URL so what you end up doing all the time is going to the WPMU DEV blog, searching for “Multisite” and clicking on one of the results.

One day you have had enough and you create a bookmark. You can now click the bookmark to achieve the same result. This is roughly what a function is for. You add a complex set of tasks to it and then perform those tasks with a simple command.

The difference between a function and a bookmark is that a bookmark is a shortcut to the solution. The bookmark doesn’t actually go to the search page, it simply remembers the URL for you. A function would actually perform all the steps separately.

Let’s look at an example where we have to use Twitter usernames a lot.

.gist table { margin-bottom: 0; }

Notice that there is a lot of repetition, we use "@" + name a lot. Let’s create a function that performs this concatenation for us, here’s the final code:

.gist table { margin-bottom: 0; }

Oh my, I’ve just made it worse right? We’ll learn about a few ways to make it a lot shorter in the next section when we learn about arrays. For now, let’s focus on how to use functions.

First of all, I created a function using the function keyword, followed by the name of the function. Every function name is followed by round brackets which contain parameters if there are any. We then enclose the contents of the function within curly braces.

A parameter is a value passed to the function. The function can then use that value to produce different results. We need a parameter here in order to produce the final username. In my case the parameter’s value would be “danielpataki” and it would produce [email protected] If I’m displaying a tweet from WPMU DEV the name would be “wpmudev” and would produce [email protected] at the end.

A function can use the document.write or console.log methods we’ve talked about but it can also return a value. Returning a value will allow you to use it anywhere you like.

When using a function you’ll need to type its name, followed by round brackets with any parameters you’d like to pass to the function.

Functions can be a daunting at first, let’s go through the code line-by-line to see what is happening.

On line 1 I defined the function. The name of the function is “twitter_username” and it accepts one parameter which I’ve named “twitter_name”. twitter_name is how we’ll refer to this value within the function. In the function, we simple concatenate an @ sign with the twitter_name and return the resulting string.

Nothing happens when defining a function, JavaScript just “knows about it” so you can use it later. On line 6, I’ve defined a name with the value of “danielpataki”. On line 7, I’m writing some text to the HTML document and then calling our function.

I’ve passed name to the function. The value of name is “danielpataki”, the function will receive this value. Let’s jump back to the function. I’ve stated that the first parameter should be named “twitter_username” so within the function the value of “twitter_username” is now “danielpataki”. At the end this value is returned and thus concatenated with the rest of the text.

Let’s take a second approach to understanding functions as well to make sure you understand how they work. Functions – like variables – are like substituting data from one place to the next, you just need to figure out what the value of everything is.

The function will return a value once it does its thing. What we need to figure it is what that value will be. Here’s a generalized way of writing our code:

.gist table { margin-bottom: 0; }

Looking at our function we see that the final line is return username;. Perfect, now we need to figure out what the value of username is since that is what will ultimately be displayed.

Right above we see the line var username = "@" + twitter_name;. So we know that username – which is the final returned value – starts with an at sign followed by the value of another variable: twitter_name. Let’s find the value of this variable.

The twitter_name variable is defined by our function itself – it is the first parameter of our function. This means we need to go back to where we used the function and look at the first parameter we passed. We used the function like this: twitter_username( name ) so we need to find the value of the name variable.

This is the variable we defined on line 6, the value is “danielpataki”. Thus we’ve reverse-engineered our function. The value “danielpataki” is passed to our function where it is referred to as twitter_name. A new variable named username is created which concatenates an at sign with twitter_name and finally returns it, giving us @danielpataki.

Multiple Parameters

Functions can have multiple parameters which can help reduce redundancy in our code – it’s all about noticing patterns. Note that each Tweet looks like this:

  • - [username]
  • . We could create a function that takes the tweet text as the first parameter and the username as the second and produces our output for us:

    .gist table { margin-bottom: 0; }

    That looks a lot cleaner! I pass the test as the first parameter and the name as the second. The function then concatenates these and returns the result. There are two things to note here.

    First of all, you do not need to create a variable to return. You can return the concatenated string without assigning it to a variable. Secondly, we don’t have a function to produce usernames anymore so we needed to switch our initial line back to 'Your twitter username is @' + name.

    Functions Within Functions

    You’ll often see a function used within another. In our example we’re creating a username within the function, but we’re also using usernames outside our function. This is a great situation to create another function.

    One function will be responsible for turning simple names into Twitter usernames. The second function will be responsible for displaying Tweets, it will use the first function to generate the username, take a look:

    .gist table { margin-bottom: 0; }

    We now have a function called twitter_username that takes a string and prepends the at sign to it. This is used on line 10 to display the username and in the tweet function as well. Note that I’ve also modified the tweet function to use document.write, making the body of our code even cleaner.


    Arrays are important parts of all programming languages. They contain a number of values within them. You can easily loop through these values or perform other operations on them. Let’s create an array that holds the number of calories eaten in the past 7 days.

    .gist table { margin-bottom: 0; }

    An array is wrapped in square brackets, values are separated by commas. Values can be any data type: strings, integers, other arrays, objects, etc.

    To see why arrays are so powerful let’s continue our Tweets example. We’re essentially displaying a collection of tweets, let’s store those tweets in an array:

    .gist table { margin-bottom: 0; }

    We can now use JavaScript’s built-in map function to iterate over (go through each member of) the array. Let’s rewrite our whole Tweets example with this in mind:

    .gist table { margin-bottom: 0; }

    The map function loops through all members of an array. The function takes one parameter – a function – which receives two arguments. The first argument is the value of the current array member, the second is the key: a numerical value that represents the order of the array member within the array. In our example I haven’t used this value.

    The map function’s first argument is a function, yet it doesn’t follow the same convention as before, it has no name. This is referred to as an anonymous function. It has no name, it isn’t defined separately elsewhere, it’s created ad-hoc when needed, usually as parameters for other functions.

    All our anonymous function does is pass the tweet text to the tweet function we’ve already written. The name is taken from when we defined our name variable originally.

    Manipulating Arrays

    We’ve already seen how you can loop through members of an array but what about modifying the array itself? Arrays have a number of functions you can use to remove, add and retrieve data from them.

    push is a commonly used one that can add a new value to the end of an array, here’s how:

    .gist table { margin-bottom: 0; }

    pop removes and returns the last element of any given array. The following example shows how the pop function retrieves the element and how that element is removed from the array.

    .gist table { margin-bottom: 0; }

    For more array functions take a look at the linked W3Schools resource.

    What To Put In Functions

    The question you may have is what to put within functions. During this tutorial we’ve created quite a few. The tweet function started out by just containing the text, then I added the

  • element to it and I finally added document.write to it as well. So should we always add everything, how do we know when to stop? We could also create a function to output all our tweets with a simple function call:

    .gist table { margin-bottom: 0; }

    As you progress you’ll learn some guidelines, you’ll know what to do and what not to do, but ultimately it depends on the needs of your application. For example, including markup like the

  • is not great.

    The tweet function should be able to display the text and the author of a tweet. Adding markup makes the function less flexible since we can only use it within lists.

    The final example above is also a classic example of bad and confusing code. We pass the tweets array to the function but the name used within the function is defined outside of the function. The data flow is hard to follow, especially if you extrapolate this to a bigger codebase.

    Focus On the Basics

    For now, don’t bother too much about the proper way to do things. Your task now is to familiarize yourself with the syntax and understand the examples we’ve been working through. Start writing code as soon as you can. You’ll make lots and lots of mistakes but that’s OK! If someone criticizes you for making them don’t forget they were once beginners, too, and made the same mistakes – joke’s on them!

    In the next lesson in this series, we’ll refine our tweets example using objects which are used pervasively in JavaScript and are immensely useful when writing code. Once we’ve wrapped our heads around objects we can start looking at jQuery to do all sorts of good stuff with WordPress.

    View @ WPMU DEV

  • Skip to toolbar