I know, I know. “I want to build something,” I hear you screaming uselessly at your screen. I get it, I do. And my very next post will make up for it, I promise. However, before we do that we have to chat about some basic terminology.

In order to help you do that, let’s open your browser’s Developer Tools so you can follow along. Start by opening a web browser (preferably Google Chrome), and then press ctrl+shift+i (hold down the ctrl button, then hold down the shift button — while still holding down ctrl, and then press the i button — again, while still holding those first two down). Alternatively, you can (in Google Chrome) click the three vertical dots icon in the top-right corner of the window, go down the menu to “More tools,” and then click “Developer tools”. You’ll get a screen like this:

Chrome Developer Tools

With this open, you can follow along with the code examples in this post.

Basic Terminology

I’m not talking about game terminology (oops… spoiled the next post), but code terminology. I’m going to keep this as simple and understandable as possible, and we’ll build on it as we go along. I’ll start by introducing some really basic vocabulary that I’ll be tossing out in later posts.

Intro to JavaScript 101

No history lesson here, although the story of JavaScript is interesting. No, I want to get to the absolute basics, and that involves me telling you that JavaScript runs in the web browser. That’s right, most of the code that you’ll be writing in the next few posts requires a web browser to see it run.

Teeny, tiny aside that is of no relevance to you at the moment: JavaScript can also be run outside of a web browser, but that’s a topic for a different time.

Comments

Throughout my example code are sprinkled some odd text smack in the middle of everything. They look like this:

// Sup?

These are called comments, and we developers put them in places as little notes to ourselves. It’s not code that the browser reads, so it’s safe to put anything behind a set of //. If you need to write a looooooooooooooooooong comment, you just wrap it between /* and */:

/*
I'm a super-long
multi-line
comment
and
I
can
keep doing
this for days.
*/

Variables

You can think of variables as containers for things we want to hold. When we use these — and we use them a lot — we expect them to be variable, hence the name. We can store all sorts of things in a variable, and they include — but are not limited to:

  • strings are what we developers think of when referring to text. A string is simply a collection of letters, numbers, or symbols.

  • numbers are pretty self-explanatory. They’re a number, like 42 or 7.

  • booleans are a fancy way of saying true (“yes”) or false (“no”). We’ll use some in the examples below.

  • objects are not self-explanatory, and I’ll get to these in a minute. For now, let’s stick to strings and numbers.

In order to use variables in JavaScript, we must declare them.

var myName;

When we declare something, we’re letting the browser know that it needs to keep track of it. In this case, we’re telling the browser to keep track of a variable (var) with a name of myName. The semicolon at the end (;) is used to let the browser know that this is a complete statement, and that it’s free to move on with the rest of our code.

But this variable isn’t very useful. It doesn’t have a value! If you type this into the Developer Tools, and press Enter, you’ll get “undefined”. We need to assign it a value, and we can do it in one of two ways.

Since we’ve already declared my variable already, I could write another line beneath it, so the whole thing would look like this:

var myName;
myName = "Rob Himself";

But if I want my variable to start with a default value, I can do the whole thing in one line.

var myName = "Rob Himself";

Let’s dissect that statement just a little, as a sort of review. var myName is my declaration, = is my assignment, "Rob Himself" is the value being assigned, and ; is my “line terminator” that lets the browser know that this is one complete statement.

How about we add to our example. Let’s use a number this time:

var myName = "Rob Himself";
var myAge = 36;

You may have noticed that I wrapped the myName value in quotation marks, but not the value of myAge. Why is that? Because JavaScript allows us to do different things with variables depending on what type they are.

A Special Note Re: Quotation Marks
You’ll often see me use an apostrophe — also called “single-quote” — in my code, and that’s because a string can be wrapped in either a set of double-quotes or a set of single-quotes. Both are valid, so long as you start and end a string with the same type of quote. The caveat to using the single-quote is when your string value itself contains an apostrophe.

"Let's get some ice cream." is a valid string.

'Let's get some ice cream.' is not.

The browser matches sets of quotes, so in the second example it stops processing the string at Let because it sees another single quote, and thinks that’s the end of the string. In order to tell the browser that the whole thing is what we call a string literal, we have to “escape” the quote in our value like this:

'Let\'s get some ice cream.'.

It’s best to pick one style, and stick with it. Just know that if you use the single-quote, you’ll have to escape strings that contain apostrophes. Alright, back to the show.

By not using quotation marks I’m telling the browser that the values can be treated like numbers, which lets me use math.

Like adding some numbers:

var addedNumbers = 2 + 2;
// addedNumbers is now 4

However, if I use quotation marks I’m telling the browser that the values should be treated like strings. If I use that same example, but with quotation marks I’ll get a very different outcome. Since you can’t mathematically add text together, the browser assumes that you’re appending one string to the other.

var addedNumbers = "2" + "2";
// addedNumbers is now "22"

And in the Developer Tools:

Numbers vs. strings
Adding numbers vs. adding strings.

What if we don’t wrap a string in quotations? Maybe something like:

var myName = Rob Himself;
// Results in a SyntaxError

We get a big fat error. Without quotes, JavaScript wasn’t sure what we were trying to do. It thought that maybe Rob and Himself were variables that we’d previously defined (we didn’t), so it gives us an “Unexpected identifier” error.

Uh oh! Gotta wrap that string in quotes!

Functions

Variables are cool, but they’re pretty useless unless we do something with them, right? That’s where functions come in. It looks a little more complicated than a variable, but once you’ve written one it’s no big deal.

function hello() {

}

That first word function is telling the browser that we’re defining a function. Then we have hello, which is the name of our function. After that are a set of parentheses (()), which I’ll get to shortly. But then we’ve got a set of { and }. These are called “brackets,” and they define the start and end points of a function.

To use a function you have to “call” it. Like so:

function hello() {

}

hello();

Let’s update this to make it actually do something, shall we? How about we have hello pop-up an alert in the browser? We’ll use another function called alert that’s baked into every browser.

function hello() {
    alert( "Hello, world!" );
}

hello();

If you paste that into your Developer Tools and hit Enter, you’ll get a pop-up message that says, “Hello, world!“. If you don’t see it immediately, click on the title bar of the browser itself. Some browsers won’t show alerts unless they have “focus”.

This is how most of those fake "government warning" pop-ups work. Completely harmless.

I used alert for a reason. It introduces the concept of arguments. When I called the alert function, I had to tell it what message to show. "Hello, world!" was the argument that I gave it. On the other end, in the function, we define that a little differently with something called a parameter. It sounds complicated, but it’s not.

function hello( name ) {
    // name is now equal to 'Rob' inside this function.
}

hello( 'Rob' );

I added name between the parentheses of my function, which lets me use it as a variable inside the brackets. So when I call hello with an argument of 'Rob', the hello function can use it through the parameter of name. All together now!

function hello( name ) {
    alert( 'Hello, ' + name + '!' );
}

hello( 'Rob' );

Passing an argument of "Rob" to the hello function, which takes a parameter of name.

But what if we want to use a function to get something for us, maybe some big calculation that we want to separate into its own function? In that case, we can use return, and have the function give us something back.

function getFutureAge( currentAge, yearsToAdd ) {
    // Create a variable to hold our calculated value.
    var theFutureAge = currentAge + yearsToAdd;

    // Here's the magic.
    return theFutureAge;
}

// Create a variable, and set its value to the output of our function.
var myFutureAge = getFutureAge( 36, 954 );

// Spit it out to Developer Tools.
console.log( myFutureAge );

Objects

Objects are a collection — or bundle, if you will — of variables. Here’s an easy example:

var author = {
    firstName: 'Rob',       // string
    lastName: 'Himself',    // string
    iceCream: 'chocolate',  // string
    eyes: 4,                // number
    wearsGlasses: true      // boolean
};

I saved this for (nearly) the end because you needed to know what variables and functions were first. And now we can finish the definition of variable because a variable can hold other variables, objects, and even functions. Check this out:

var myBigMassiveObject = {
    name: 'Biscuit',
    type: {
        gender: 'boy',
        animal: 'dog',
        breed: 'pug'
    },
    age: 7,
    poopsAlot: true,
    bark: function() {
        console.log( 'Woof!' );
    }
};

There’s a little something for everyone there. Clearly, my object describes a dog. My dog Biscuit, specifically.

This is Biscuit!
Biscuit, the magical sun doggo!

These types of things are useful for organizational purposes. In big applications where you’ve written lots of code, objects can help you keep things nice and tidy. So how do we get or use that object?

var myBigMassiveObject = {
    name: 'Biscuit',
    type: {
        gender: 'boy',
        animal: 'dog',
        breed: 'pug'
    },
    age: 7,
    isGoodBoy: true,
    poopsAlot: false,
    bark: function() {
        console.log( 'Woof!' );
    }
};

// Here comes the sugar.
var age = myBigMassiveObject.age;
console.log( age );

var breed = myBigMassiveObject.type.breed;
console.log( breed );

myBigMassiveObject.bark();

// Bonus round! Let's change some things!
// Before:
console.log( myBigMassiveObject.name );
// After:
myBigMassiveObject.name = 'Sausage';
console.log( myBigMassiveObject.name );

Basic Logic: If/Then/Else

We know how to create and manipulate variables, we’ve tinkered with functions, and played with objects. To do useful things, we have to use basic logic. For example, in the myBigMassiveObject above, I want to change the value of isGoodBoy if the value of poopsAlot changes. Let’s see how that’ll work:

var myBigMassiveObject = {
    name: 'Biscuit',
    type: {
        gender: 'boy',
        animal: 'dog',
        breed: 'pug'
    },
    age: 7,
    isGoodBoy: true,
    poopsAlot: false,
    bark: function() {
        console.log( 'Woof!' );
    }
};

// Let's create something that we can compare with.
var biscuitPoopedOnTheFloor = false;

// If he pooped on the floor, then Biscuit poops a lot and isn't a good boy.
if ( biscuitPoopedOnTheFloor == true ) {
    myBigMassiveObject.poopsAlot = true;
    myBigMassiveObject.isGoodBoy = false;
}

console.log( myBigMassiveObject );

Nothing changed. That’s because biscuitPoopedOnTheFloor has a value of false, and our condition was only set execute the code inside the block if biscuitPoopedOnTheFloor was set to true. If we make that change:

var biscuitPoopedOnTheFloor = true;

Now the console shows us the updated object values for poopsAlot and isGoodBoy inside the myBigMassiveObject variable. What if we have more than a simple binary choice (“binary” choice means that there are only two possible outcomes), or something should happen if our condition wasn’t met?

var myBigMassiveObject = {
    name: 'Biscuit',
    type: {
        gender: 'boy',
        animal: 'dog',
        breed: 'pug'
    },
    age: 7,
    isGoodBoy: true,
    poopsAlot: false,
    bark: function() {
        console.log( 'Woof!' );
    }
};

// Let's create something that we can compare with.
var biscuitPoopedOnTheFloor = false;

// If he pooped on the floor, then Biscuit poops a lot and isn't a good boy.
if ( biscuitPoopedOnTheFloor == true ) {
    myBigMassiveObject.poopsAlot = true;
    myBigMassiveObject.isGoodBoy = false;
}

// If he didn't poop on the floor, he should bark at us.
else {
    myBigMassiveObject.bark();
}

And finally, we have the else if, for occasions where we need to string together multiple possible choices:

var myBigMassiveObject = {
    name: 'Biscuit',
    type: {
        gender: 'boy',
        animal: 'dog',
        breed: 'pug'
    },
    age: 7,
    isGoodBoy: true,
    poopsAlot: false,
    bark: function() {
        console.log( 'Woof!' );
    }
};

if ( myBigMassiveObject.isGoodBoy == true ) {
    console.log( 'Biscuit is a good boy.' );
} else if ( myBigMassiveObject.poopsAlot == true ) {
    console.log( 'Biscuit is not a good boy because he poops a lot.' );
} else {
    console.log( 'Why is\'nt Biscuit a good boy? He doesn\'t poop a lot.' );
}

Arrays and Loops

Sometimes — many times — we need to efficiently create a bunch of variables, and to do so it makes a lot of sense to store them in an array. Array variables get a special definition:

var myDogs = [];

Those two square brackets ([ and ]) mean that this variable is storing more than one of something. This one in particular is empty, since we haven’t put anything in it yet. Arrays can hold simple strings — called a string array, simple numbers, or more complex objects.

I’ll do a little less explaining on this one, since I know you’re up for the task of putting it all together with everything else you’ve learned today. I’m going to create a collection of my doggies.

var myDogs = [];

// Add Biscuit.
myDogs.push({
    name: 'Biscuit',
    age: 7,
    gender: 'boy',
    breed: 'pug',
    bark: function() {
        console.log( 'Biscuit says, "Woof!"' );
    }
});

// Add Bubbles.
myDogs.push({
    name: 'Bubbles',
    age: 2,
    gender: 'girl',
    breed: 'havanese',
    bark: function() {
        console.log( 'Bubbles says, "Woof!"' );
    }
});

// Make the first doggo in the collection bark.
myDogs[ 0 ].bark();

// Let's LOOP through our collection, and have each dog bark!
myDogs.forEach( function( doggo ) {
    doggo.bark();
});

// Alternatively, we could do it like this:
for ( var i = 0; i < myDogs.length; i++ ) {
    var doggo = myDogs[ i ];
    doggo.bark();
}

What did we do?

  1. Declared an empty array named myDogs.
  2. Added Biscuit to the array by using push to add an object describing Biscuit.
  3. Added Bubbles to the array by using push to add an object describing Bubbles.
  4. Made the first dog in the array bark; in this case, that’s Biscuit. He was added first.
  5. Used forEach on the array to make each dog in the array bark.
  6. Used a for statement on the array to make each dog in the array bark.

What’s up with the 0 in myDogs[ 0 ].bark()? JavaScript — and most other languages — are what we call “zero-based,” meaning that they do all of their internal counting starting at 0 and not 1. Biscuit was the first dog added to the collection, and to pull the first item from an array means using 0. If we’d used 1, Bubbles would have barked instead.

How To Loop: forEach

forEach is an internal function built into JavaScript specifically for arrays. It takes — as its argument — a function that takes (as its argument) a single item from the array. We start with the 0th array item, and the doggo value is Biscuit. After the last line in the forEach block happens for Biscuit, it moves on to Bubbles. Then the doggo value becomes Bubbles.

To make it more clear and easier to understand, let’s rewrite it a little.

// Separate the function from the forEach.
function makeDoggoBark( doggo ) {
    doggo.bark();
}

// Let's LOOP through our collection, and have each dog bark!
myDogs.forEach( makeDoggoBark );

How To Loop: for

for is another internal function built into JavaScript, and requires a little more explanation to get going. We obviously start with the for, but then we add a whole bunch of stuff right? The easiest explanation is that we’re simply counting from 0, and then doing something with the doggo at that number location in the array. Let’s look at that again:

for ( var i = 0; i < myDogs.length; i++ ) {
    var doggo = myDogs[ i ];
    doggo.bark();
}

This block — var i = 0; i < myDogs.length; i++ — is actually three statements rolled into one. Here’s how the browser interprets that:

  1. var i = 0; is a new variable set to the number 0.
  2. i < myDogs.length; is an if statement that checks whether the variable i is less than the number of items in the myDogs array.
  3. i++ is an increment of i. After each loop, add 1 to i.

So if we break this down using our array of two dogs, it could be expressed like this.

  1. i is 0.
  2. Check to see if 0 is less than 2. If it is, doggo becomes the item in myDogs at position 0 (the first item). Make doggo bark.
  3. i adds 1, and 0 + 1 = 1.
  4. Check to see if 1 is less than 2. If it is, doggo becomes the item in myDogs at position 1 (the second item). Make doggo bark.
  5. i adds 1, and 1 + 1 = 2.
  6. Check to see if 2 is less than 2. It is not, so we leave the loop.

Note that when dealing with numbers in the sense of code, we must be very precise. 2 is not less than 2. 2 is equal to 2. Which is why the loop stops.

Conclusion

Yeah, I thought this was going to be shorter honestly. But I don’t want to just assume that you might know something, so it’s good to explain this as much as possible. Reread it as many times as you like, and if it doesn’t “click,” that’s totally okay. You can do it, and I’ll prove it to you.

In the next post, we’re going to start creating a game!

Boom! /drops mic

Care to Practice?