Getting Started With JavaScript (And How It Compares to PHP)

JavaScript has been in the news a lot lately, and for good reason. There’s a growing need for WordPress developers to “learn JavaScript deeply.” However, making the switch from PHP can seem overwhelming at first glance.

In our opinion, even if PHP is your only programming language, you should find the switch to JavaScript comfortable enough to begin hacking away at a few scripts in no time. Once you understand how the basic building blocks of JavaScript are put together, you’ll have a solid grounding that will enable you to explore the more complex aspects of the language.

In this guide aimed at beginner WordPress PHP coders, we’ll take a cue from Learn X in Y Minutes’ superb primer on JavaScript. We’ll directly compare how JavaScript code should be structured and written to how things are done in PHP. First, however, let’s talk about a little of WordPress’ history with JavaScript!

WordPress and JavaScript: A Love Story

The relationship between WordPress and JavaScript is a fleeting one but has many developers enthralled by the possibilities. We’ve discussed how the two are being combined many times in the past, most notably in our article Everything You Need to Know About JavaScript and WordPress. We’ve also looked at JavaScript frameworks, and essential libraries for you to work with. What’s more, there is plenty more where that came from in the pipeline.

As for how JavaScript is being incorporated into WordPress, progress has been slow on paper. Of course, there’s still a lot of work going on behind the scenes. For example, WordPress.com is powered by the Calypso codebase:

The Calypso codebase home page.

The interface is built on a server-side layer of Node.js – in short, a runtime library that helps you develop JavaScript applications. What’s more, WordPress’ new Gutenberg editor is slowly becoming JavaScript-friendly. Learning the language ‘deeply’ has therefore never been more important.

The Differences Between PHP and JavaScript

In a moment, we’ll delve into the coding differences between PHP and JavaScript. First, however, it’s worth looking at the more ‘global’ distinctions between the two languages.

PHP is likely a programming language you already know intimately. It’s a server-side scripting language that’s mainly used for web development but has other general uses too. It’s weakly-typed, and you’ll most commonly find it intertwined with HTML in .php files. PHP is nearly 25 years old and is currently on its 7th iteration. PHP 7 performs much better than its PHP5 predecessor, according to many tests.

JavaScript is similar in a number of ways. It’s also a weakly-typed, dynamic, and interpreted language. It makes up one of the three core components of the web, along with HTML and CSS, and is therefore used on a vast number of websites to provide dynamic, interactive content to users. It’s actually a subset of ECMAScript, which also powers ActionScript and JScript. The former is Adobe’s take on the language, and JScript is Microsoft’s version (which is primarily used for Internet Explorer).

In a nutshell, both languages have a lot in common. This prompts the question: Why is JavaScript being emphasized all of the sudden? The answer isn’t totally clear, although this article explains a bit more on the subject, and Matt Mullenweg’s announcement of Calypso offers further insight. Regardless, it’s become clear that JavaScript is a language you’ll need to begin learning if you want to ‘future-proof’ your WordPress skills.

How JavaScript Compares to PHP (4 Key Elements)

While what follows is nowhere near an exhaustive list of the languages’ major elements, it provides the foundation you need to start building basic JavaScript programs. You’ll also find that you can begin extrapolating from these elements on your own, and we’ll give you some pointers to help you take your learning even further before we wrap up.

1. Variables

Before we begin, it’s worth pointing out that while PHP requires code to be wrapped in <?php ?>, JavaScript doesn’t need this element. As such, we’ll omit that from any PHP code examples for ease of reading.

Let’s start simply, by looking at how variables are constructed. In PHP, of course, you’ll prefix every variable with a dollar sign ($):

$boolean = true; // or TRUE or True
$boolean = false; // or FALSE or False

However, in JavaScript, you don’t need to do this. What’s more, because the language is dynamic, you don’t need to declare types either. For instance:

var fooVar = 5;
var barVar = 'This is a string';

Declared variables that haven’t been assigned are set to Undefined. You’ll also notice that variable names are written in ‘CamelCase’, and still require a semi-colon at the end, similarly to PHP.

You can place multiple variables on one line by using commas:

var fooVar = 2, barVar = 4;

Plus, JavaScript uses shorthand notation for math operations:

fooVar += 5; // equivalent to fooVar = fooVar + 5; fooVar is 10 now
fooVar *= 10; // now fooVar is 100

// Short-hand for adding or subtracting one
fooVar++; // now fooVar is 101
fooVar--; // back to 100

Of course, variables are usually easy to get your head around. The complexities arise when you start dealing with other aspects of the language.

2. Control Structures

If loops represent a fundamental way of controlling flow throughout your programs. Thankfully, both PHP and JavaScript have the same structure for if loops:

if (x) {
    Do something!;
} elseif (true) {
    Do this instead;
} else {
    Do a final thing;
}

The same applies to for loops…

for (var i = 0; i < 5; i++){
    // will run 5 times
}

…and while loops:

while (true){
    // An infinite loop!
}

As an aside, you’ll also notice that commenting is the same with both PHP and JavaScript, in that you use a double backslash (//). However, while PHP also uses an octothorpe (#), JavaScript uses the ‘slash-star’ (/* */) approach.

3. Arrays and Objects

Much like control structures, arrays also follow a similar format within JavaScript as they do in PHP:

var myArray = ["Hello", 45, true];

As you’ll see, these are ordered lists of any type. Indices start at zero, much like many other languages. They’re also accessed similarly to PHP:

myArray[1]; // = 45

However, one major difference between PHP and JavaScript is that the latter doesn’t support associative arrays:

$associative = array('One' => 1, 'Two' => 2, 'Three' => 3);

Instead, JavaScript uses arrays as numbered indexes and ‘objects’ as named indexes:

var myObj = {key1: "Hello", key2: "World"};

They’re essentially unordered key-value pairs, and are accessed as you would an array, although you can also use dot notation to access a key-value pair:

myObj["my other key"]; // = 4

// You can also use dot notation, provided the key is a valid identifier.
myObj.myKey; // = "myValue"

You’ll notice that objects look very similar to dictionaries or maps in other languages such as Python, and are arguably neater to read than in PHP. However, it may take some time to get used to this system, so be prepared for some healthy debugging during your first few scripts.

4. Functions

Finally, we come to functions. Much like many other PHP elements, they have a similar look in JavaScript. First, here’s an example of a basic function in PHP:

function my_function () {
    return 'Hello, World!';
}

echo my_function();

The corresponding JavaScript function is practically the same, although you don’t need to echo or print the function to call it:

function myFunction(thing){
    return thing.toUpperCase();
}
myFunction("hello, world!"); // "Hello, World!"

However, JavaScript functions are ‘first-class objects’, which means they can be assigned to different variable names and passed as arguments to other functions. This event handler is a perfect example:

function myFunction(){
    // this code will be called in 5 seconds' time
}
setTimeout(myFunction, 5000);

In case you’re wondering, setTimeout isn’t actually part of JavaScript, but is provided by web browsers and can be found in Node.js. Functions can get much deeper than this, of course. So we’d encourage you to skim through the Learn X in Y Minutes docs before putting all this guidance into practice.

How to Explore JavaScript More Deeply

As we made clear earlier, this piece outlines only the very basics of JavaScript as compared to PHP. Therefore, if you’re looking for a deeper dive into the language, you’ll need some additional resources.

Of course, we’d first recommend browsing the Torque blog, as we have plenty of helpful articles related to learning JavaScript from scratch. We’ve already mentioned a couple, but here are two more:

We’ve also looked at how to begin using JavaScript within WordPress. Although that piece is a few years old, it’s still a solid example of how the platform handles JavaScript.

Finally, you’ll also want to dig into some general-purpose tutorials for learning the language as a whole. We recommend starting with Mozilla’s MDN pages on JavaScript, before picking up a good book. Eloquent JavaScript is, for our money, arguably the best resource on the market.

Conclusion

It’s been talked about almost to the point of tedium, but JavaScript and WordPress are becoming more aligned by the day. Ever since the ‘call to arms’ was put out, developers have begun to “learn JavaScript deeply“. However, for those who are still just coming to grips with PHP, learning a new language can seem like a steep mountain to climb.

This post has looked at how PHP code compares to JavaScript, and offered a side-by-side comparison of the two. Understanding these four basic elements is the key to unlocking the whole JavaScript language:

  1. Variables
  2. Control structures
  3. Arrays
  4. Functions

Are you looking to learn JavaScript as a PHP developer, and if so, what resources are you using? Let us know in the comments section below!

Featured image: AhmadArdity.

Tom Rankin is a key member of WordCandy, a musician, photographer, vegan, beard owner, and (very) amateur coder. When he’s not doing any of these things, he’s likely sleeping.

The post Getting Started With JavaScript (And How It Compares to PHP) appeared first on Torque.