This lesson assumes you know how to create variables of these basic types:
- Strings / Text
- Boolean (True/False)
- Arrays (Lists)
…and that you can mix and match them creatively.
Here’s an example for a basic user account:
Remember: Variables of all types can be placed almost anywhere in your code, for example if you have a list of colors:
and people can pick which color they like best, you can do this:
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!
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:
You could just put:
in your code, run it and then type
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
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:
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:
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.
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.
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!)
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:
Let’s wrap the function inside of
()‘s to group 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.
and even further reduced with added imagination for visualization purposes:
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:
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:
If you really want to bake your noodle
Take a look at this:
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?
Is an overly simplified way of expanding
Real World Example
Most websites out there use jQuery to speed up development and help with browser compatibility among other things.
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
_ 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:
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:
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!