Intro to Web Programming - Javascript Pt. 3

This lesson assumes you know how to create variables of these basic types:

  • Strings / Text
  • Numbers
  • Boolean (True/False)
  • Objects
  • Arrays (Lists)

…and that you can mix and match them creatively.

Quick Review

Here’s an example for a basic user account:

1
2
3
4
5
6
7
8
9
10
11
12
var user = {
loginCount: 14,
signupDate: 1417066602, // Unix Time -> http://www.unixtimestamp.com/
wantsNewsletter: true,
flags: ['moderator', 'staff', 'beta'],
socialNetworks: {
facebook: false,
twitter: "@example",
googlePlus: "Example"
}
}

Notice how this example uses one of each type? It’s quite common to find this occurring in most software written in Javascript/Node.js.

Remember: Variables of all types can be placed almost anywhere in your code, for example if you have a list of colors:

1
var colorNames = ['blue', 'red', 'green', 'purple', 'pink', 'black'];

and people can pick which color they like best, you can do this:

1
2
3
4
5
var brentsFavorite = 0;
var tomsFavorite = 2;
var daniellesFavorite = 4;
console.log("Danielle's favorite color is " + colorNames[daniellesFavorite] + "!");

We used a variable in the place of an index for another variable - this can make your code tidy and help you avoid having code duplication. In this case we can also add more colors in the future, or replace the english names for the colors with another language and not have to update all the people’s favorites in order to show them!

Moving Forward

I’m going to assume you’ve gotten the hang of using JS Bin by now or something else that’s similar.

I’m going to use console.log() in my examples so that when you run the code it spits everything out to the console automatically so you can clearly see it. However, at any time if you feel comfortable using the console directly you can just run the code and peek at the values of variables instead.

For example, if I write:

1
2
var name = 'Brent';
console.log(name);

You could just put:

1
var name = 'Brent';

in your code, run it and then type name into the Javascript console to see the same result. It’s completely up to you!

Note: Sometimes it’s easier using console.log because it runs automatically at specific points within your code. I will mark the cases where you should use the console.log with a comment that looks like this: // use log

Functions

So there is another type of thing that can be stored in a variable (but doesn’t have to be) that is extremely powerful. They’re called functions, some languages call them methods. Their purpose is fairly simple, to take things you give it (parameters) and perform an action on them, and then sometimes output something back.

You can always identify them by the word function being used upon their creation, that and they have some pretty telltale brackets:

1
2
3
var hello = function() {
console.log('Hello there!'); // use log
};

This particular function doesn’t need any parameters/input, and serves the sole purpose of greeting people through the console. (Thrilling, I know!) It also doesn’t return any sort of value.. it just sort of does its thing and moves on.

If you were to write this in your code and run it, nothing would happen though. Much like the other types of variables, you’re assigning a value to hello (in this case) and not doing anything with it.

The funny thing about functions is they only run when you explicitly pass something to them (in this case we have to literally pass nothing) — like so:

1
2
3
4
5
var hello = function() {
console.log('Hello there!'); // use log
};
hello();

Notice the empty brackets after hello(); - this is where we’re literally passing in nothing. If you ran this code, you’d see ‘Hello there!’ pop up in your console.

If you didn’t put the ()‘s in there, then it would just spit out the actual function itself (its definition, not the actual result of the code inside) and it would never get run. This is handy if you want to pass a re-usable function around your program, but we’ll get to that much later!

Any code you could imagine can be put inside a function - think of it as a wrapper for code that compartmentalizes it and (sometimes) gives it a name and purpose.

Your goal when writing functions is to have each one perform a single task, typically ones that are going to be needed to be used more than once. Once a function gets really big and starts doing multiple separate things, you can actually just break the code into multiple functions and call them inside one another! Don’t be afraid to mix and match just like with variables!

Taking some input

Functions are only mildly useful if you don’t pass them any information to work with. So let’s make a greeting function that does something a little more complex.

You can pass things in, by adding them inside the ()‘s — you give them names in the function() definition and you put the values you want to have the function do something with inside the brackets when calling it/running it.

Example:

1
2
3
4
5
var greet = function(name) {
console.log('Hello there ' + name + ', how are you?'); // use log
}
greet('blog reader');

In this example you can see the function greet takes a name, this is just a variable name I came up with, you can choose your own if you like. Inside of the function name can be used anywhere just like other variables.

When greet('blog reader'); is run, the value blog reader is passed into the name property of the function, making it available inside while running the code!

Sidenote: If you run this code and type greet('Your name here'); in your console, you can play around with the function in realtime to see it in action!

Scopes and Closures

This is a more advanced topic than most people need to get into right away, feel free to skip it and come back later

One of the harder things to explain about functions is how they isolate the code inside of them. Let’s say you use the variable called name in your script. This is a very common name for a variable, so what happens when you use another script on your page that also uses name in it?

…They’re going to both be very unhappy and be messing each others’ values up.

So what do we do about this? Well functions compartmentalize everything inside them. So why not just run our entire program inside a function to protect it from the outside world? (and to protect those poor souls from us!)

Example:

1
2
3
4
5
6
7
var program = function() {
var name = 'Brent';
console.log(name); // use log
};
// Don't forget to run the actual function
program();

If you run this, you’ll notice that the name Brent gets printed to your console as one would hope, however if you actually click over to your console and type name into it it’s not going to give you the expected result (either undefined or in the case of JS Bin you’ll notice it spits out something odd - this is a case of what we’re trying to avoid actually happening in real life).

So it does make things harder to poke at with the console, but it prevents your program from colliding with others and is generally a good practice. You can always wrap your program in the function after you’ve tested and built it on its own.

Now wait a minute, something doesn’t seem right here…

Our function is still a variable, and in this case it’s called program which is just an arbitrary name I selected. But that name itself is actually going to potentially collide with other scripts running on my page.

Note: When you hear of ‘Global Namespace’ people are referring to variables that aren’t protected by a function/closure.

So how do we get rid of the name of our function?

We could do this:

1
2
3
4
function() {
var name = 'Brent';
console.log(name); // use log
}

But Javascript will get angry at us because without a name there’s literally no way for it to ever be run. So we need to bring back a way to run it.

Let’s wrap the function inside of ()‘s to group it:

1
2
3
4
(function() {
var name = 'Brent';
console.log(name); // use log
})

So Javascript is still going to be angry, because we’ve just told it to make a group with an anonymous (think nameless) function inside of it but still have absolutely no way of running it.

Remember: In order to run a function, you need to pass something into it even if it’s just empty brackets: ().

So the easiest way to visualize the state we are at now is to pretend that by grouping the function we’ve essentially turned the entire thing into a one time use variable.

Think:

1
2
3
4
5
6
7
8
9
10
11
(function() {
var name = 'Brent';
console.log(name); // use log
})
// is the same as:
var pretendThisNameDoesntExist = function() {
var name = 'Brent';
console.log(name); // use log
};

and even further reduced with added imagination for visualization purposes:

1
2
3
4
5
(...stuff_in_here...)
// is the same as:
pretendThisNameDoesntExist

Both of these things are essentially the same, you treat the bracketed stuff like it were a named variable. And how do we call a function that has a name? By putting () on the end of it. So how do we call a function that has no name? By putting () on the end of it like so:

1
2
3
4
(function() {
var name = 'Brent'; // use log
console.log(name);
})();

I put a semicolon in there for good measure.

If you run this now you’ll see that the code inside gets run, but you cannot access name from your console because it’s protected by the function’s enclosure.

Likewise you cannot use name outside of that function in the same code:

1
2
3
4
5
6
(function() {
var name = 'Brent';
// Console log WAS here
})();
// Now it's out here (and doesn't work anymore):
console.log(name);

If you really want to bake your noodle

Take a look at this:

1
(console.log)('Hello!');

Say what? Well it does the same thing as a console.log('Hello!'); would do, only it grouped the function console.log — Yes, all this time you’ve been using functions and might not of even realized it! You were just using built in ones sitting in the ‘Global Namespace’.

See the similarity to our program’s function though?

1
(function(message) { /* Fancy stuff here to output to the console */ })('Hello!');

Is an overly simplified way of expanding console.log

Real World Example

Most websites out there use jQuery to speed up development and help with browser compatibility among other things.

jQuery is just a library of handy functions built in regular Javascript. They usually get you to build your program inside of code like this:

1
2
3
4
5
(function($) {
// Your program here
})(jQuery);

This looks a little strange, but consider what we just learned about using functions to close off our program. jQuery wants us to do this right out of the box so we have a smooth experience and don’t risk the chance of bumping into our scripted neighbors.

The only addition here, is that our nameless function friend accepts a value — which jQuery has decided to name $. Frankly it could be called bling or $$$$ or _ or any other equally strange but compatible variable name. The dollar sign just seemed nice and short, and looked neat in code so they chose it.

jQuery needs to be able to be used inside of other people’s scripts - which means it can’t completely be closed off like our code is. It has to run the risk of a single collision in order to make itself known to the world, and in order to play it safe they called that variable jQuery, the name of their own library. It is a single variable that they chose to build in the ‘Global Namespace’ so that everyone can play with it.

So why do I need to pass it into my function?

Well, you really don’t. But you’d end up typing jQuery out a LOT of times in your code to use its features, so it was nicer to essentially rename it to $ to be shorter. That $ is only visible to code inside of your program’s function, and so it won’t wreck any other scripts on your page that also use the $.

So next time you write something like:

1
$('.blogpost').show();

You can think of it as actually running the function jQuery() and passing in the text ‘.blogpost’ and it’s giving you back an object full of functions. One of them is called show() in this case.

You can even break it down like this:

1
2
3
var $ = jQuery;
var blogPostObject = $('.blogpost'); // Magic black box of jQuery
blogPostObject.show(); // Show is just a regular function on an object that jQuery gave us

Summary

So we’ve taken a look at making re-usable code with functions, and allowing those functions to take in a parameter so they can be more useful. And for the braver of you, we learned about using functions to close off your code from the outside world and how to do so by using an anonymous function that essentially calls itself.

Next up I’ll focus on more function magic, accepting multiple parameters, returning values, putting functions into objects, objects into functions, all sorts of madness!