Check out my latest book of drawings!
Rapid Transit

Javascript Functions, Closures, and the IIFE
June 29, 2018, 9:14 am

When writing code in Javascript or any programming language, one of the core concepts that a developer has to wrap their heads around is the function. If variables are values to be referred to at a later time, functions are whole sets of code to be referred to later.

Function

function myFunc() { // Do something }

You can also define a function as a value, or as an anonymous function. Normally functions are hoisted to the top of the code and run first, but an anonymous function is created inline with the rest of the code around it.

Anonymous Function

var myFunc = function() { // Do something }

There is value in both of these methods. It is important to know your options and explore their relevance. But there are even more options.

Sometimes it can be handy to define a function that defines it's own lexical scope. This allows local variables to be set up statically.

Closure

function foo(){ var id = 5; var bar = function() { console.log(id); } return bar; } var foobar = foo(); foobar();

This series of code has some very interesting implications for scope and how to create functions that have their own values. The id variable only exists inside the foo function, but the foo function returns the bar function as a value, and since the bar function was made inside foo, and after id, it also has access to the id value. Closures allow you to segregate your values and give unique scope to parts of your project. This becomes especially useful when you want to write code for libraries and larger repositories.

Immediately Invoked Function Expression

(function() { // Do something })()

Then there is this beast. A function with no name. No real declaration, but put inside of an expression syntax that fires it off immediately. What is the point? Why wouldn't the do something code simply be code, why does it need to be wrapped up like this?

Well, defining a function anonymously allows it to be passed around by value in a much more flippant manner. Most often anonymous functions are used for callback reasons. However, if it tries to access values that were created outside of it's scope it accesses them dynamically at their current value. This can be an unwanted effect, that is most often run into when defining a callback function inside of a loop.

If you make 3 buttons dynamically in a loop, and have them each print out the iterator value on click, all of them will print out the last value, because at the time of clicking, the iterator would have only its final value.

for(let i=0;i<3;i++){ $("body").append($("< button>").click(function() { console.log(i); })); }

This exact situation is when an anonymous function called immediately to provide closure to its scope is most effective. But it gets more complicated. Any method that is expecting a function to be passed into it must receive a function. And a closure that returns a function as a value is a goofy thing to look at.

Anonymous Closure Callback Immediately Invoked Function Expression

var i = 5; $("button").click( (function(id) { return function() { console.log(id); } })(i) ); i = 10;

Now, that's just weird to look at your first time. It will start to make sense the more you end up using it. The IIFE is being passed a variable in order to give closure to it's current value. The i variable gets passed in at the end of the closure, and then is referred to on the inside as id. This means that no matter what might happen to i in the future, when the click happens, the value of i has been stuck into the static value of 5 in id.

[edit] So um... turns out that loop example doesn't produce the result I said it would which means.... That's not actually a problem when you use the let declaration, instead of the var. But the final example still matters.

A minor suggestion
August 17, 2016, 8:51 pm

I have always held off suggesting books for students to read when learning things in my class. Mainly, because I believe that someone else's methods and speeds of teaching will often interfere or even hinder someone learning things in my class. I think websites like Code Academy and Lynda provide brilliant tools for people to learn things at their own pace and at multiple levels. But being that I teach high level classes, I often find these sites either move too slow, or never reach a proper level.

I have, however, recently read a book that I feel is quite good, and I could recommend to people wanting to learn programming using the Javascript language. Eloquent Javascript is really quite a good book. I often tell my students that really the only thing they need is a reference for the guidance they will get in a class. In that case, I would usually just point someone at Javascript Pocket Reference

I made a breathing app...
March 5, 2016, 9:52 pm

You may have seen something about it on facebook or twitter. I'm working on making it embeddable for others to put on their websites. Let's try that here.

Copy this code onto your website to embed the xhalr breathing app into it.

<iframe src="http://www.xhalr.com" width="400" height="400" frameborder="0" allowfullscreen style="max-width:100%"></iframe>

A contextual difference
July 11, 2015, 11:27 am

There is a major difference between fundamentally learning how to program, and learning a new programming language.

Let's look at an example.

$a = 0;

If you said, "That looks like code!", congratulations, it's your first day. Have a lollipop. If you said, "That's a variable assignment", congratulations, you seem to know how to do basic programming. If you said "That's a variable assignment in php", congratulations, you seem to know the basics of PHP. If you said, "That's a variable assignment of the number zero, which has a basic value type of Number, to a variable with the designation of $a, in the php programming language", then congratulations, you're a huge nerd! But what about when the language is less obvious, or you don't know that particular language. Should you still be able to figure stuff out?

function sqr(num:Number):Number{ return num*num; }

Now, if you didn't know that was Actionscript code, that's ok. Not everyone does. But you should be able to use your knowledge of basic programming to figure out what is going on. It seems to be a function definition. Something called sqr(). I'm not sure what those colon parts are, but it seems to be a basic type of value, so I'll bet it's saying num will be a number. I can only assume then by the second :Number placement that sqr() is also supposed to be a number? The function seems to be multiplying the number by itself, then returning that value.

Did you see what I did there? I don't know Actionscript 3. I learned Actionscript 2, back in the day. Actionscript 2 did NOT have type casting. I found that code on the Adobe help site when I searched for "actionscript function return value".

Learning to program means you should be able to know a few basic concepts, and recognize those concepts in any language.

  • What is a variable?
  • What is an array?
  • What is a function?
  • How do I if else?
  • How do I loop?

Those are the core concepts of programming. And they are (mostly) language independent. If you can figure out how to do those things, you can probably write anything in any language.

... after about 2 months of intensive study in that new language just to get anything to freaking show on screen...

It can be difficult in the early days of learning your FIRST programming language to measure the difference between learning that language's syntax and learning the essentials of programming in general. It might not even ever become clear to you until you attempt to learn your second programming language. Suddenly things that weren't important before can become very important. Suddenly things that were so hard before can become easy. Changing languages is a difficult task, and learning your first language can feel like a monumental challenge. It isn't until you learn to differentiate the fundamentals of programming, from the idiosyncrasies of a particular language, that you will truly begin to reach your potential.

An hour of code
December 9, 2014, 12:38 am

This week is Hour of Code week. It's a national event to try to get kids interested in programming. I'm a big proponent of everyone knowing at least a little about how to program. I think it all seems so scary, because most people don't have a simple enough place to start.

I am doing a presentation at the Apple Store in downtown San Francisco this Thursday, December 11th. It is going to show you how you can make a simple image gallery with a little bit of html, css, and javascript. This is for absolute beginners to get an idea of what is possible with a relatively small amount of code. If you want to get a head start, the code I'll be making can be found here. I'll be talking about the programs I use, and how getting started is the biggest hurdle.

I personally think everyone should have their own website. Not everyone has to put in my level of effort, but to be fair, I've put in nearly 20 years of effort, and now you can just reap the benefits of my experience. But I definitely think everyone should have more than an auto generated webpage that's just created by wordpress or wix. Make a little code and create something.

If you're interested in web tutoring, in San Francisco, I would love to help you get up and running, so hit me with an email.

Here is a list of important links for this presentation.

  • 0