Intro to Web Programming - Javascript Pt. 1

Earlier this year I was invited up to Vernon, BC to teach the first of two very basic intro courses to Javascript. Last year I taught this for the first time at Accelerate Okanagan with great success.

Thanks to the encouragement of the people who’ve attended both sessions, I’ve decided to try get in the habit of posting the material online for anyone to benefit from. So here’s the first part to my web programming series!


Modern web applications are typically broken down into two separate, but related systems. Here are the different components of each and their responsibilities:

Front-end

  • HTML
    • The structure and content of your website
  • CSS
    • The look & feel of your website
  • Javascript
    • The interactivity & data components of your site

Back-end

  • Web server (Apache, Lighttpd, Nginx, IIS, etc)
    • Serves static content like images, files and routes requests to the platform
  • Platform (Node.js (Javascript), PHP, Python, .NET, and many more)
    • Serves up information (data) to your front-end code
    • Manages authentication / user accounts (if needed)
    • Takes user input from front-end and figures out what to do with it
  • Database (MySQL, MongoDB, Neo4j, and many more)
    • Stores, indexes and retrieves information you need to keep around

These systems run independently, but work together in tandem to create a full experience. Each component and system can even be built separately by different people/teams of people and made to work together.

For the sake of this lesson I’m going to focus on Javascript.

Why Javascript?

  • It’s the only programming language that works both in a web browser (front-end) and on a server (back-end), so you don’t have to learn two different languages to get a single job done!
  • It has a huge community willing to help, lots of questions already answered, and a lot of documentation
  • Lots of components are built for you, ensuring that you don’t have to reinvent the wheel when building things
  • Works on any computer: Windows, Mac, and Linux

Getting Started

Since Javascript is built into every modern web browser, we’ll start by using a website that let’s us play freely with Javascript without having to worry about setting up servers or proper website structures right away.

The site I usually use to play with code is jsfiddle.net - however it’s missing a built in console so you can see the things you’re playing with easily.

For the sake of this lesson I’m going to recommend using jsbin.com, feel free to open it up in a new tab or browser window so you can follow along.

Setting up JS Bin:

  • Click the file menu in the top left, and choose ‘New’ so we have a good simple starting point.
  • Let’s simplify the interface by turning off the ‘HTML’ view (leftmost of the top middle buttons), close the ‘Output’ pane as well.
  • Turn on the ‘Console’ pane and you should only have two sections open, Javascript on the left and Console on the right

Now we’re ready to experiment a little with Javascript!

Variables

Variables! The building blocks of anything and everything you create. Much like the variables you might encounter in math class when dealing with algebra (yuck), their purpose is to act as a placeholder for information.

Things you can store in variables:

Numbers

1
var age = 28;

Type this code into the Javascript area of JS Bin

This simply puts the number 28 into the variable age - you can check that it worked by using a handy utility of Javascript called the ‘Console’ which lets you log things and inspect them:

1
console.log(age);

Insert that on the line after you set age and click the ‘Run’ button in JS Bin (Near top right) - it should spit the result out in the ‘Console’ pane on the right. You should see the number 28 appear in this case. Every time you press run, it will keep adding to the console.

Text (Known as ‘Strings’)

1
2
3
var name = 'Brent';
// or
var name = "Brent";

Along the same line as the number, this puts my name Brent into the variable called name - you can check it just like you check the number by using console.log(name);.

Notes: You can put sentences, and even paragraphs worth of text into a variable - just remember to keep it all inside of either single or double quotes! If you need to include a quotation mark of the same type as which surrounds your text then you’ll have to use a little trick called ‘escaping’. Here’s a couple examples:

1
2
3
4
5
6
7
8
9
// A single quote/apostrophe inside of a string that uses single quotes to surround it:
var greeting = 'Welcome to Brent\'s Javascript example';
// or
var greeting = "Welcome to Brent's Javascript example";
// Another type of example:
var greeting = "Welcome to Brent's \"so called\" example";
// or
var greeting = 'Welcome to Brent\'s "so called" example';

Notice that a backslash (\) is used immediately before the quotation mark that needs to be escaped, this lets Javascript know that it’s not intended to be the end of the content and to just treat it like normal text.

If you use the opposite type of quotations around the text there’s no chance you’ll confuse Javascript and you can just type as normal.

Feel free to play around in JS Bin until you feel comfortable with how this works.

True or False (Known as a Boolean)

1
var likesJavascript = true;

It’s always useful to use true/false as values, since they’re much easier to work with than strings or numbers for cases where you need to remember a simple yes or no value.

Lists of things (Known as an Array)

1
var likes = [ 'computers', 'woodworking', 'games' ];

The square brackets [ ] tell Javascript that we’re dealing with a list of things, any time you see them you’ll know too!

You aren’t limited to one type of data inside a list, you can mix and match as you see fit - let’s say I like the number 5, the example could look like this:

1
var likes = [ 'computers', 'woodworking', 5, 'games' ];

Which would be perfectly valid, although a little unconventional.

Note: There’s no reason you have to keep everything on one line, you can keep your code a lot tidier/more manageable by using line breaks:

1
2
3
4
5
var likes = [
'computers',
'woodworking',
'games'
];

Just remember to include all of the commas, brackets and quotes - they’re easy to miss.

Reminder: console.log(likes); will allow to you to see that you’ve set up your list properly.

Objects (Collections of other variables, stored by name)

1
var socialMedia = { facebook: 'brentacus', twitter: '@seratonik' };

Objects are identified by curly braces { }, there are a few other things in Javascript that use curly braces too but you’ll soon be able to confidently pick out the objects visually.

Like arrays, objects are great for holding multiple values - the biggest difference is that you get to name each of the values you put in it, giving them context. Objects are one of the most powerful things in Javascript, almost everything you interact with in Javascript is secretly an object, whether you realize it or not!

Why store things in an object vs. just having individual variables?

By grouping information together by relevance you are able to pass it around as a whole. For example: If you have a user logged into your site, would you rather type name, email, joinedDate, facebookAccount, twitterAccount, etc every time a part of your code needs user info, or just pass an object called user around that contains everything inside of it (and can be extended easily later without restructuring your code).

Functions (We’ll get to these later)

1
2
3
var isLearning = function() {
return true;
};

Functions are extremely handy in Javascript, I just wanted to give you a little teaser - but we’ll get into them in the next part of this intro.

Putting it all together

Now that we’ve learned about the different types of variables, let’s review it all together:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var age = 28;
var name = 'Brent';
var likesJavascript = true;
var likes = [
'computers',
'woodworking',
'games'
];
var socialMedia = {
facebook: 'brentacus',
twitter: '@seratonik'
};

This is a basic user profile! Given that we just learned about how objects can group related information together and make it easier to pass around our program, let’s try clean up this a bit and combine it in to a single object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var user = {
age: 28,
name: 'Brent',
likesJavascript: true,
likes: [
'computers',
'woodworking',
'games'
],
socialMedia: {
facebook: 'brentacus',
twitter: '@seratonik'
}
};

This object called user holds the exact same information as the set of variables we started with. Notice how you can actually have objects inside of objects and lists inside of objects - there’s no limit to how you can mix and match things together to come up with a data structure that works for you.

Note: That inside of an object you use a : instead of a = to set values, and in between each thing you’re setting you must use a comma , - these things are easy to forget and mis-type causing a lot of headaches. If you find your code not running properly it’s a good chance that something small is missing.

You should be able to now console.log(user); and see a neatly formatted copy of your user object spit out in the console. This is more powerful than you’d think!

Remember: It’s entirely up to you if you want to put things on one line or multiple; however, it’s usually best to put line breaks after commas and brackets/braces. There are a lot of different coding styles out there, it’s good to try follow what the majority of people use so that your code is familiar/readable for as many people as possible.

Review

Once you master these different ways of storing information, you can start imagining all of the types of things you can store:

  • Blog articles
  • Stats for your D&D party
  • Contact cards for your friends
  • and almost anything else.

While this article only reviews how to store things in variables and the different types, we’ll soon get into working with the information in these variables so you can bring a program to life!

Recommended Resources

  • Code Academy - Interactive lessons that step you through programming