Robert: [0:05] Well, good morning Amsterdam. I hope you're having a better morning than I have, it's probably because my room is so freaking big that I got lost this morning, and I tripped on the stairs from the main room going through the corridor to the bathroom. Otherwise I'm good, so... when I got invited to talk here at Fronteers, they asked me "Who do you want as a support act? Who do you want to warm up the crowd for you?"
[0:33] I said "Yeah, what about Jeremy Keith?" You want to help the new guys, the up-and-coming guys, and you know get some exposure for them. I'm happy for Jeremy. Let's take it from the top. I'm Robert, apparently, and I think I'm going to give a talk and tell you about how things work and how you should do things and such. We need to establish a good relationship. You need to know who I am, and what I stand for. So let's start with the obvious things. Yes, I know I'm balding. I do feel like a ninja turtle, and I do have the goatee to cover up for it. Where it still grows, let it grow.
[1:20] I'm from elsewhere. [laughter] There are some similarities. I'm not saying anything, people have pointed that out. I'm from Sweden, and yes, everything you have heard is true. It is the promised land. We love our flags. The problem, though, is when you travel around Europe and give talks, people always remind you of the first depiction of the Euro coin, [laughter] and I don't know what happened.
[6:49] And you know, if you do learn it, it's going to be fun. It hurts at first, like most things, like some things that happened last night, but eventually, you come to enjoy it. And, whereas you were about 10 years ago when it was just slow and sluggish and killing websites, it's become really, really fast today. Web browsers put so much effort into interpreters and compilers and such to make it run as fast as possible, to get a smooth experience. It's always mandatory to have a diagram, right?
[7:58] I want to have some sort of theme for my code examples, because otherwise you make up some weird shit about dolphins and crap, and people wonder what they paid for. So, I'll try and have a red line through my talk and having code examples with Forrest Gump, hence the title of the talk. So, actual code. If you start from the beginning, you just declare a variable. We have the var key word. We give a name to it, that's Forrest. We have functions. We give it a name and it returns a certain value. That's pretty basic.
[8:34] Then of course, we have "if" statements and "switch" statements. This is just a little check. If that is "True", do this. With switch of course, you have different cases. If you have a certain value you do that, otherwise you do that. All good.
[8:53] Then we're going through a few characters of code that do lots of things when we start to create objects and arrays. So, the topic up here is an object literal. This is just how to create an object, it has a property, a first name, a value of Forrest.
[9:10] The second one is how to create an array. Just use the angled brackets and have my value printed within there. Now, I have an array to work with.
[9:23] We also have something labeled shorthand assignment. Which is basically in this function, if you send in a value in "boxOfChocolates", it will equal to "True" and it will assign that value to the variable "life". If it's "False" or doesn't have a value, you just have the two piped characters here so it just defaults to "Snickers bar" instead.
[9:45] You also have Ternary Operators which is basically just an "if else" saying as a one liner. Within the parentheses, we have the looking value. If it's "True", it's going to be a "I gotta find Bubba!" value. Otherwise, it will default to "It's ok."
[10:03] We also have something called Short-circuit logic. The reason I bring this up and I hope it makes sense but in a lot of code I see and through audits and such, people just keep on nesting "if" clauses. It's like a tree of "ifs" and then some code that actually does something.
[10:21] The easy thing here is you can just do the one "if" clause. You check if object, or 'obj' here, actually exists and if it does, they can start checking values on it without having a variable.
[10:58] The rest of it are objects. They all stem from big mother objects. A part of objects is having arrays and dates, functions themselves are also coming from the object. We also have regular expressions.
[11:17] If we have all of these data types, usually when you code you want to check what kind of data type a certain variable has. If we have the variable's "firstName" here, we'll just have the data type "string". The function will determine as a function and then you can make different code branching depending on that and how you want to work with it.
[11:36] We also have and you saw before with having the objects and arrays, the problem here is if you use "typeof" of an object, it's an object. If you use it on an array, it's also "object". It just comes from the object data type.
[11:51] That doesn't really help us. It's sort of like the scripting errors in Internet Explorer here. "Null = Null". Yeah, of course. But why? What happened?
[12:02] The same thing here with "typeof". What you do instead to compliment and use instead of "typeof" if you're going to have a case between an object and an array, you can use something called "instanceof". You can check the variable and you check "instanceof". If it's an actual instance of the array object, then you can see if it's an object or array.
[12:42] It's disgusting when you hear your own body noises amplified a lot. I would not want that at home. [laughter]
[12:54] So, looking at different values, they are not actually what they seem. Like I said before, we have "Null", we have "Undefined", and also here we have the number "Zero", or "False", or empty string. If you try to check all of these values with an If, they will all default to "False".
[13:40] I do like this picture. The thing is, in the military and especially in the American military, is that if you are forced into doing something you don't want to and it's put on tape or something, you cross your fingers to show that you are forced into doing that. That you didn't really want to do that.
So, I like that. That this military was apparently forced to shake hands with Hillary Clinton for the press or something but he wanted to send a message to the "buds" showing that he doesn't really like Hillary.
[14:13] Looking at coercion, what it actually means, I'm blaming my cold that I can't pronounce coercion correctly and I also have the mandatory quote from Wikipedia, it's basically forcing something to behave in a manner that it doesn't really want to.
[15:23] If it is yes, then you can actually check the values. It's a really good way to make sure that nothing goes in there when you don't expect it to. Yeah, as I said.
[15:39] It also happens when you are trying to concatenate a string. Like you have a string "5" and you add on the number 6 or 7. This could be a really common case like Jeremy was talking about before, having a number field. If you take the value from a form field, it's a string.
[15:59] They might try to add that up. If you add a string with numbers, it just defaults into a string and it's not really what you expected.
[16:06] To make sure that doesn't happen, you can use something like "parseInt". What "parseInt" does that it takes the value and turns it into an integer, actually a number, and then you can add it up. That is going to work.
[16:25] This is not a pause. I just need a drink. [laughter]
[19:04] And it's not mandatory, but it's just a good way to write it. If you have an object constructor, it should be uppercased the first letter, like a big F for Forrest. As you saw before, you can also use the "object literal" approach. You can just assign the variable directly, and use the curly braces here, and then you have the different values. And the difference here is that you don't use the "this" keyword. You don't have "this.firstname", "this.lastname" instead you just have first name, last name.
[19:36] That's what you saw in the previous file, you had the equal signs and semicolons. But in object literals, instead we just have colons in the middle, and then we have regular commas separating the different values. You also need to make sure that after the last value, you don't have a comma, because that would throw some web browsers off. You can also iterate over all of the properties in an object that you have created. You just use a regular for-loop and just log out the different values.
[21:32] But also, the prototype of the entire ForrestAsGrownup object is the ForrestAsChild object, which means that the ForrestAsGrownup object will have have everything from ForrestAsChild, plus the new things you add to it. And then it has this method of its own, which is a little accident with the bathrobe. So, if you first create an instance of this object, you have the grown-up object, OK? var forrest = new ForrestAsGrownup();. And then when it runs the ruinsBathrobe-method, and returns the value that you had on the grown-up object.
[24:14] If that is undefined, I can just define my own push method and fix the web browser for that. And good thing about this, of course, is you don't write your own push method for everyone. If it's implemented, fine, and you can attach anything, but if it doesn't, I can help you on the way. And I can just run the code here and use the push method on the array, and it would work in virtually any web browser. I'm not really sure what I used, what kind of drug I used when I choose my pictures, but this is about scope when things are accessible and when they aren't.
[25:33] So, if you're going to have a local variable, always remember to specify the var keyword. And also, you can start nesting functions. This, I've pretty much worked out before the presentation. I had to run down and do my thing, but if you have a function, "meetingJFK" here, it's just a global function. You can access it from anywhere, but within that function, you have the forrestReply-function. And the forrestReply-function, it's just local to its outer function. So, you can only access forrestReply from within that function. Outside of it, it doesn't really exist as the rest of the world sees it.
[26:55] And if I call on a "document.body", it's going to be "body", of course. So that first parameter is actually not being sent in. It's just setting the scope of the receiving function, like what's the context I'm working in. The only difference between the call and the apply methods is that call, you can sent in comma separated values as parameters to your receiving function. With apply, you send in a collection instead, or send in an array, which is pretty useful because you can begin to pipe things all the way over.
[27:31] You can use the apply method, and just send in arguments, as we saw, for the function. You don't need to specify any value in the array, you can just keep on passing an argument to another function, then the new function will have arguments from the previous function. And the good thing to know about scope, is of course, as you saw before, with the global scope, when you omit some things or forget some things, you pollute the global scope. Polluting the global scope is bad, when it comes to coding and when it comes to factories.
[29:59] And then it remembers that value for eternity. Then if you call action, because action has suddenly become a function which was returned from the first function, it will just remember the value of "what". Then the key thing to look at in the code here is, if you look at the inner function being returned here is that inner functions will always have access to its outer function's variables. So the inner function here can always assess the value of "what", even after the happens function has been run through.
[30:34] Usually, you talk about this and it's just freaking scary and weird and you don't want to know what triggers behavior like that. But if you just try and break it down here, it's that the inner function with the "what" value here, the "what" value will always be remembered. The the last part isn't technically 100% accurate, but just to make it easier to understand. The new action variable is as if the value of shit, which is the value of the "what" parameter, have been hard-coded in. So it will always remember that "what" was shit. I'm sorry. [laughter]
[31:21] So, just emphasizing, inner function must always remember the values of its outer function's parameters and variables. The best way, though, I mean, my slides are going to be available online if I ever access the WiFi, the best thing to learn here, whatever you're doing with coding, is take some code that someone like me claims actually works, and break it. You know, remove things, test stuff, see how it behaves, because that's the only way to properly learn. You can read books forever, but you need to test and practice how it works and how different environments actually behave in real life.
[32:03] So, to begin a more proper example, and this is the thing that most people have gone through, is that you can just... I'm going to create three links in my documents, and I'm going to give them value, which is link zero, a link one, etc., and then I assign an onclick function. When you click the link, you sort of expect the value of "i" for that link. So if you click the first link, you want it to be zero, if you click the next link, you want it to be one, et cetera.
[32:34] The weird shit here is, if you click the middle link and expect one, it says three. Why does it do that? The reason it happens is that I was talking about it, inner functions always remember the value of outer variables so you see, if I click here, it just assigns a function and we'll just remember the value of "i". As you can see, in the loop, "i" has been counted up to three, so it won't care what value it had when onclick was actually assigned. It will just remember that oh, the loop went on and ended up as three.
[33:10] So no matter which link you click, it's going to say three. Talking about closure, the way you can get around this is, when you assign onclick, you can assign a function that's being run right away. Talking about playing with yourself, self invoking functions. So what happens is that, at that moment in time, just that specific iteration in the loop, you send in the value of "i". That value is assigned to the index parameter, and as you remember, inner functions remember the value of outer parameters. The inner functions being returned, the function actually being run when you click on the link, will remember the value of index when it was being sent in. Which means that it was zero for the first link, one for the next link, two for the last link and such. Magic.
[34:59] So forest.getFirstName(); will get the first name. But the first name variable at the top here is not accessible, because it's just within the function. And again, inner functions have access to outer variables and parameters. You could also, and it's just a matter of taste, Christian was the first one who showed this to me, in the return statement if you don't want a lot of code there, you can just you know, the value on the left is the API way of exposing the name of method, and the value on the right, which is the same here, is just the name of the function, the firstName function here, to run. And the value on the right can be anything, just to make it easier. And it's just a matter of taste if you want to do the thing on the previous slide or on this slide.
[35:59] When I try to find pictures for slides, you always think I want something good that you can sort of connect. There was really no good picture for namespacing, so this is the best I could come up with. [laughing] You do the best on what you have.
[36:50] At the top we have the forrest object as before. And at the bottom we have Lieutenant Dan, the poor guy in the wheelchair. And the getFullName method on Lieutenant Dan, what it could do, and we talked about inheritance before and prototyping, sometimes you can use namespacing instead and so have things side by side and not necessarily children of each other. So what you can do here to getFullName method on Lieutenant Dan, it that you can call the method of the Forrest object but you use the .call method and set the scope.
[37:27] This basically means that the line at the bottom here, this and the receiving one, is actually the Lieutenant Dan object. And this is also a good way to protect your code. The only really global thing we have is the movie object. The rest of the things are just properties on the movie object not a number of different global object names. Yeah, what I said.
[37:55] And like I said about messing around with code, what you need to do is try things. And things are bound to break. And luckily, or hopefully, none of us program airplanes or something, it's just web pages. So just, you know try it out and then you see how it works, and then you learn from that.
[39:00] And you also use another variable for all the strings that you want to concatenate. Assign it to "content" and instead of just adding onto a string, instead I'm working against a dot in their HTML property (???) over and over and over. And if you do it like this, things might work out well. [laughter]
[39:21] Another way, and it's probably more a personal taste thing, if you have lots of variables in a function you can use the var keyword over and over and over. But you can also just comma separate it. So if you have the var keyword here and you have different variables. You have the rich variable, and then you just have comma, and then you have the next variable, and the next, and the next. So it's just one time to extensiate when you create the variables.
[39:50] And you know peoples favorite things, I'll try to be careful of what I say here, people always discuss, what's the ultimate loop? How to I conquer the world with the one true way of doing it? And you know there can be only one and all that. Which is not really true, but I'm not going to put any more value into that.
[40:09] But if you have a loop like this that gets all the paragraphs in the document, it iterates over them. And [coughs] sorry, I'm dying here. And it iterates over them, and also what it does with the allParagraphs array here, is that it does constant look-ups into that array. So the first problem is here, that when you have a for loop, you have three parts when you define the for loop. The first part is the variables, what happens at the first time you just start the for loop. The one in the middle and the one on the right, that happens for every iteration in the loop. And if you're going to go through or over a lot of different values that's an unnecessary performance hit.
[40:59] So what it means here that you have the allParagraphs.length, you need to check length for every time it goes around the loop. And that's not a good thing. Another thing that you don't want to do is that for each time that you go around the loop. Go around I don't want to keep everybody waiting. For each time you go around the loop you don't have to create variables within the loop. You have to create them outside the loop instead, because it's just an unnecessary performance hit. And also talking about doing lookups on the allParagraphs array here, it's that to look up an array could cost you, especially if it's huge array.
[41:38] So instead of that, if you try and make the code simpler here, is that at the beginning of the for loop, we declare all of the variables that we're going to use. And then we have them ready. What this also means is that... I have an error in my code. I'm sorry. Of course, the "l" variable after the zero should equal the allParagraphs.length. So you check the length of allParagraphs once, so now you don't need to check it. Then "i" can only compare to "l", which is a fixed value and not a lookup on allParagraphs.
I also define the link variable at the beginning of the loop, so I don't have to define it in the loop for each iteration. And at the end, I have a new variable, called "paragraph", which does, for each iteration loop, it does one lookup in the array and then uses the variable instead to do things to that value, like checking the ClassName or appending a new childnode to it or something like that.
[42:48] And my favorite thing, and usually I can't use this because Douglas Crockford is giving a talk at the same conference later on his thing, but he's not here. And Jeremy mentioned before about semicolon insertion, stealing my material.
[43:55] The curly braces are just considered an empty block. An object that you put there, but you can't access it anyway. Fine, I'll let it be there.
It's one thing for you, but there's also... You're to hand over the code to some poor guy in the end. So you need something that works and you need to agree on good standards. Overall, JSLint is a very good way to approach that. To conclude, I know that some of the things about scope and closures, it could be a bit scary. And some people think that, "OK. I will never grasp this. I cannot learn this." But I want you to go away with knowing that, if that guy can get that girl anything is possible in this world. If you have a dream... No, I'm not going to go down that road. Do you know about this, by the way? It's Macaulay Culkin, this one little Home Alone kid did a movie when he was about 10.
[45:47] Then he went on drugs for 15 years and then he started dating her. I don't know where I went wrong in my life. Another thing to say is that, usually when I give talks, and you know about Twitter... If you have seen me giving a talk, it's mandatory to follow me on Twitter. You don't have to read it or like it or anything. But the thing is that the other speakers, they're mean. And they have so many followers. They look at my follower count. It's like, "Why are you going to give a talk? You're no one." So please follow me. You can spam me with porn, that's fine. But please. OK? [laughter]
[46:28] Thank you for listening and take care. [applause]
Robert: [46:44] Yes, do we have any questions? I feel like a deer in the headlights of a car.
Man 1: [46:54] Hi, I was just wondering...
Robert: [46:55] I'm sorry, hold up over here, oh. [laughter]
Man 1: [47:02] Hi. Should you really ever use a double equals instead of a triple? Or is there any reason that you should use a double instead of using a triple?
Robert: [47:14] So the question is if you have equals signs in talking about type coercion that if you use two equal signs or three equal signs, could you use both? I would say use three equal signs all the time. Just to make sure that you don't run into anything weird.
Man 1: [47:31] Yeah, I know that's what I was thinking but I saw you had double ones up there so I thought to ask.
Robert: [47:37] I'm going to fake and say that it was just an example, not how to do it, if that's OK. [laughter]
Robert: [47:46] Yes. There's someone.
Man 2: [47:50] What's your opinion about for and then var i? Years ago I read that declaring the var i in the for loop is also bad performance. But still I always see for and then var i. Should you do it outside so first var i and then for i is lower than number, or doesn't this make a difference?
Robert: [48:14] Right. So the question is when you start the loop like you declare the variable i, like var i=0, should you do that in the loop or is it a performance hit; should it do it before the loop?
From what I've seen and it hasn't really been that much of a performance hit. I mean it could be, you can talk to someone like Andrea Giammarchi who's from Micro-performance Optimization, and but, I haven't seen any real difference in practice if you define it, you know, before the for loop or at the beginning of the for loop. And sure, it is good to think about that, I am preaching about that. But, at the end of the day that could help but it's way more important to look at what we have inside the loop, you know what happens for each situation. And if it's many iterations, that's the big performance hit.
[49:15] I see people.
Man 3: [49:20] With the object literal and the instantiation of object, if you know that your object's only going to be one instance of it is there really a difference between, I mean is there an advantage for having an object which you instantiate which is the object literal?
Robert: [49:38] So the question is, is there a difference between the object literal or and so, a constructor to create an instance of it.
Man 3: [49:44] Yeah.
Robert: [49:45] Right? To me I haven't seen any real performance difference, but I think it comes down more to style than how you work with it. Firstly, I'm a fan of the object literal, I think it's, you know, the syntax is more terse and easier to work with. But you know if you work with other people, and especially some of the Google work is you know doing it the other way around, I mean sort of the object constructor approach and showing it that way. But if it's just one instance, you know go with whatever works for you.
Man 3: [50:20] Thanks.
Robert: [50:28] No further enquiry? No? OK, thank you. [applause]