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.
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:
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.
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.
alert('Write any message here') within the script tags and reload the page.
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.
I’ve mistyped the code from before using
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.
Writing Into the Document
<head> section or within the
</body> section – it makes pages load a lot faster.
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:
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.
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.
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.
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.
1.6 million WordPress Superheroes read and trust our blog. Join them and get daily posts delivered to your inbox - free!
Let’s look at an example where we have to use Twitter usernames a lot.
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:
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 “@danielpataki”. If I’m displaying a tweet from WPMU DEV the name would be “wpmudev” and would produce “@wpmudev” at the end.
A function can use the
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.
name with the value of “danielpataki”. On line 7, I’m writing some text to the HTML document and then calling our function.
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:
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.
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
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
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:
<li> - [username]</li>. 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:
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:
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.
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:
map function to iterate over (go through each member of) the array. Let’s rewrite our whole Tweets example with this in mind:
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.
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.
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:
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.
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
<li> 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:
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
<li> 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!