A Brief Introduction to JavaScript Libraries
I was fortunate enough to speak at OKCjs this afternoon. OKCjs is our local usergroup, and I can say the best bunch of nerds I’ve ever met. I could write an entire post on how sweet, welcoming, and helpful these people are to beginners. In large part because of the people I’ve met at OKCjs, I am further in nine months than I could’ve hoped to be in years of self-learning.
Seriously, if you are in Oklahoma City, definitely check out OKCjs, and Techlahoma and see all the cool stuff that is going on around here. It might surprise you!
Today I spoke at Lightning Talks, which is essentially a mish-mash of short, very insightful talks. Other people who spoke included Nicholas Lindley, Jonathan Yarbor, Raymond Lewallen, and Adam Rackis. All of their talks were fantastic! It’s really great that we have so many knowledgeable speakers willing to share what they know in the Oklahoma City area.
In my short five-minute talk, I went over JavaScript libraries.
Basically, a library is a collection of JavaScript functions that you can include in your project. Someone has gone in and written out these nitty-gritty functions so you can have the benefit without the nitty-gritty. I am deeply appreciative of anyone who writes libraries.
A framework is also a collection of JavaScript functions. Essentially ‘library’ and ‘framework’ can be used interchangeably. However I did find an explanation of the differences between the two that I really like. (Note: I will say library throughout this post, but I am referring to both libraries and frameworks.)
A library will allow you to pick and choose which functions you would like to use. Much like a physical library doesn’t require you to read every book in a specific order, and you can check out whichever books you want.
A framework will provide a very specific way to write your code. And much like the frame of a physical structure, if you don’t follow the framework layout specifically, things can begin falling apart.
There are loads of different libraries out there, and I’m not in the business of telling people that one tool is superior to another. I will tell you to research a library before you start using it, and really consider whether or not you need it. A library is adding complexity to your project. If you project doubles in size from your library, consider if you can do complete the project without the library.
I said this several times during the talk, but I really believe it can’t be said enough.
If you can’t write the code without the library, please don’t use the library.
It may seem nice in the short term to just get your work done and out the door, but you will do far better in the long run if you can write the code without the library. Don’t take shortcuts in your learning, you’ll end up shortchanging yourself.
Also beware of using multiple libraries together, as this can cause compatibility problems. Using more than one library isn’t bad, you just need to research and make sure you can use them together.
And whatever you do, make sure the version of the library you are using has the word ‘stable’ in there somewhere. You don’t want to use a version that is still in development!
You can see the slides from my talk here.
The Truth About Falsy Values
You can’t handle the truth!
JavaScript can’t either, which is why it uses type coercion to convert most values to a ‘truthy’ value. What does this mean?
Well, the true boolean value is just ‘true’, right? That is accurate, but it’s good to know that JavaScript also interprets the majority of other values to be true as well. Meaning, if they are place in an if statement, JavaScript will go ahead and run the if statement because the statement isn’t false.
Obviously JavaScript interprets the boolean value ‘false’ to be false. But there are a few values in JavaScript that are interpreted to be falsy, and as such, JavaScript will not run an if statement that is dependent upon these values. The values are:
- 0
- ””
- null
- undefined
- NaN
Other than being a handy little bit of trivia, what is this useful for? Well it’s not something that will always be useful, but it’s definitely worth filing away for future reference. Here’s an example of a use-case I ran into lately.
Recently I wrote a game for a friend’s baby shower. (You can play it here, if you’re interested. Or you can check out the code here.)
One version of the game included pausing when the player jumped on the bad guy. I wanted the bad guy to be destroyed on unpause. But the problem I was running into was that Phaser, the platform I used to build the game, runs the update function pretty much constantly, and I have to destroy the villager in the update function (because it’s called immediately after the game is unpaused).
But here’s the rub: there wasn’t always a villager that needed destroying. Since that was coming back undefined, my whole game was breaking.
Having the falsy value trivia tucked away, I was able to work around this relatively easily.
if(currentVillager) {
currentVillager.destroy();
}
In the function where the player jumps on the villager, I pass that specific villager to a variable called ‘currentVillager’. Then in the update function, I have an if statement checking for ‘currentVillager’. Lucky for me, JavaScript interprets undefined as a falsy value, and skips my code if there isn’t a villager in the ‘currentVillager’ variable.
Pretty handy!
TL;DR
If you have some code that only needs to be executed if a variable has a value (or isn’t undefined), you can wrap this code in an if statement and take advantage of truthy and falsy values!
Much Ado About Callbacks
Have you read or seen Shakespeare’s ‘Much Ado About Nothing’? It’s a pretty funny play. The short story is that two characters have a thing and want to get hitched, except a rumor gets out that the girl has been hooking up with this other dude (not her boyfriend). Chaos ensues because it was back in the day and that sort of behavior was unseemly. But in the end it’s all ok because it was just a rumor, and didn’t really happen.
Much Ado About Nothing.
That pretty much describes my relationship with callbacks up until recently. I was really intimidated by the idea of them, and if I saw them I tried to find some other way of accomplishing my goal without using callbacks. However this mentality – appealing as it may be in the moment – is not conducive to growing and learning.
Recently I was working on a game in Phaser. (I’ll post more about it soon.) I wanted to call certain functions upon specific key presses. For instance, when the user pressed the spacebar, I wanted their character to jump. I tried really hard to find a way to do this without using a callback, and I came up empty. So it was time to me to face my fear and figure out how to work with a callback.
Turns out in looking at them more and really focusing, I was really getting intimidated and worked up over nothing.
So what is a callback exactly? Well, a callback is a function that is passed in as a parameter. It might look this:
spaceKey.onDown.add(jumpUp, this);
You can see more code here.
So basically what this is saying is “when the user presses spaceKey, call the jumpUp function.” In this case, the jumpOn function is only called when the player presses the spacebar.
Here’s another example.
module.exports = function getExtName(dirName, ext, callback) {
var result = [];
fs.readdir(dirName, function(err, files) {
if(err) {
console.log(err);
return callback(err);
} else {
for(i = 0; i < files.length; i++) {
if(path.extname(files[i]) == '.' + ext) {
result.push(files[i]);
}
}
return callback(null, result);
}
});
};
And here’s the function being passed in…
function outputToConsole(err, data) {
if(err) {
console.log(err);
} else {
console.log(data.join('\n'));
}
}
mod(filePath, extName, outputToConsole);
You can see more of this code here.
As you can see above the callback function is returning data, whether it be the error, or the data that the function is manipulating and then returning. This is done as a callback to the fs.readdir function because we need the data to be read in before we do any manipulation on it. Otherwise the outputToConsole function would likely run before the data was even read in. That would in turn mean that data would be undefined and the function wouldn’t work.
Notice that in these functions when I pass in callback, I do not pass it in with parenthesis. This allows the function to be passed in, but not called until I choose for it to be called.
The nature of JavaScript is that it reads your code from left to right, top to bottom. It runs any functions in the order they are called. But there are cases (like the examples above) where you don’t want the function to be called when it is read. You’ll only want it to be called when something else happens…like when you get the correct user input, or you want it to wait until after your data has been read in.
This is why callbacks are so handy!
Think also about if you are waiting on the user to give your program data. Any manipulation of that data would have to wait until the data has been typed in. (Otherwise the variable holding your data would be undefined, right?) This is another good example of when you might want to use a callback.
TL;DR
Callbacks aren’t as scary as they seem. Write up your function and pass it in as a parameter (without parenthesis) and then you can call it only when you actually want it to be used. This allows your other functions to continue running while you wait for user feedback, or to access the information you need for your callback.
So... I just gave my first conference talk
So I just gave my first talk at Tulsa Tech Fest last Friday. I’ve spoken at OKCjs (my local usergroup) before, but those were short 5-10 minute lightning talks. This was a full length presentation. And it was about Star Wars. (You can check that out here.)
Regarding the talk itself, I decided to give a beginner talk. Why is that? Well, I don’t feel very qualified to give any other type of talk! Beyond that, I am all about beginner talks. Why is that?
When I attended my first conference (which was not that long ago, if I’m being honest) I was a total newb and I didn’t get much out of it. Through no fault of any person, it’s just the talks were at a higher technical level than I was actually at. I did learn one thing about Node servers, and that was really it. I remember being so bummed, because I thought I was going to learn a bunch and I didn’t.
Not to say I regret going. It was a really fabulous networking opportunity, and I did meet some really cool people. Also I’m able to go watch the videos of the conference and understand far more than I did then.
But suffice to say, I wanted to give a beginner talk because I wanted to attend beginner talks. Be the change you want to see, right?
I did learn a lot from speaking, and I wanted to share some of the things I learned.
Start on time
My talk was scheduled for 75 minutes, or 60 minutes for the presentation and 15 minutes for Q&A. But my room filled up really quickly, and before 3pm, my scheduled time, we had already run out of seats. I didn’t think anyone else would come in, so I started my talk more nearly 10 minutes early.
Learn from my mistake and wait until your scheduled start time, or even two or three minutes after. I had people continue wandering in after 3pm, and they missed the first 10 minutes of my talk, which was a bummer because I’m hilarious. ;)
Engage your audience
I thought I did enough with choosing a unique and funny topic. But the truth is I ended up just sitting in a chair talking to my audience for close to an hour. This is pretty tough for me because I can get really nervous, but I should have been up and moving around, and trying to engage the audience more.
Ask the audience questions
Don’t expect your audience to have questions immediately. They might think of questions later on, or (and this is especially the case in beginner talks) they might be too nervous to ask whatever question they have in mind. Go into the talk planning to ask questions to the audience to get a conversation going. To give you an idea, I came with an example of a project they could create a program for. I asked them how they would handle this program, and then moved on to the plan I created.
But I missed an opportunity to engage my audience further by working with them to make a full plan for their program – entirely their own. Listen for when your audience starts talking, and focus on that, even if it means deviating from your notes.
Come in with code
I didn’t do any live coding, nor did I give any code examples. My talk was about using your skills to better your community, and while I gave examples of projects, I didn’t give any code examples. If I have the opportunity to give this talk again, I will do more of a workshop, and actually use the tools I’ve mentioned, instead of just talking about them.
Just start talking!
Even though I had several spots where I could have done better, I am still really proud of myself that I did it! It was really nerve-wracking to get up in front of people and talk. There’s a fear of rejection – and that’s really tough to overcome.
What is your first talk going to be about?
In Defense of Asking
I’m really writing this post more for myself than for anyone I have spoken to, but I think most people will be able to get something out of this post. I’ve been debating about this post for a while, trying to find the right words and all that. I think this is something that needs to be said, and I hope someone reads it and asks the question they’re been afraid to ask.
I think feeling competent is an especially difficult thing for a self-taught coder, like myself. I started out in journalism (yes, that’s right – at newspaper. They DO still make those.) and that might explain my love of incorporating literature into my posts. Or I might just be weird.
I started teaching myself on Codecademy, and if you’ve ever done it alone, you’ll know how tough it is to learn a language on your own. There is no reference point, it’s like walking around in the dark with holes in the floor. If you fall through the floor you have no idea why, only that you did something wrong.
So beyond yammering about how I learned coding, what am I getting at here? Well… I tend to apologize when I ask any type of question. And that’s if I ask the question at all. So often I will hold on to a question because I’m not sure of the terminology, or I’m afraid that it’s going to make me look stupid and reveal the lack of knowledge I have and everyone will know that I don’t really know what I’m talking about and the sky will fall and the universe will IMPLODE.
Ok, maybe that’s a long shot. But I still don’t want to look stupid, and asking might make me look stupid, so I don’t ask. When there comes a time I do ask the question, it usually looks something like this:
- “I hope I’m not bugging you but…. <question>”
- “Sorry to bother you…”
- “This is probably really obvious, but….”
- “Is this a bad time?”
- “Sorry if this is stupid…”
You get the idea. I frequently apologize and I’m super hesitant to ask. And these people are my friends! But asking is a scary thing. In a field where knowledge is currency, you are expressing that there is something you don’t know.
Spoiler Alert: Everyone has something they don’t know.
(If this is something you are really having trouble with, check out this video on Imposter Syndrome.)
The main thing I was to say here is that if you haven’t figured it out yet, it’s ok to ask. Give it the old college try on Google, and try to make sense of what you find. Get on JSFiddle and try to use it yourself. Open up the console and mess around to see how it works.
BUT
If you’ve done this and still aren’t getting it. ASK SOMEONE. And whatever you do, do not apologize for asking.
If anyone tries to make you feel bad or stupid for asking your particular question, they are an asshole. Period. They do not deserve your time. Don’t ask them again, and keep asking and Googling until you get it.
The best thing I have ever found for grasping a difficult concept is just working with it. Pull open the console and start logging stuff out. Try it a different way. Put log statements throughout your function in different places. Tweet out your question.
Just don’t give up. And definitely don’t apologize for asking.
Happy Friday.