[MUSIC PLAYING] DOUG LLOYD: So by now we're old pros at web programming, right? And we've covered several languages in individual videos. And now let's do one more, JavaScript. First the good news, JavaScript is a modern programming language much like PHP whose syntax is derived from C, so that's a good place to start. It's about as old as PHP, as well, having been around about 20 years. It was invented around the same time as PHP. And JavaScript is actually pretty fundamental to the user experience of the web. In fact, there are three languages that I would say sort of make up the user experience of interacting with the website, html, css, and JavaScript. And so now let's talk a little bit about JavaScript. The bad news, though, with JavaScript is that it sets a lot of rules for itself, and then it breaks them. And JavaScript can actually be kind of challenging to learn, because it's unlike C and PHP, which are very structured and have very rigid rules for how things can work. JavaScript has kind of gotten so flexible that maybe things aren't going to work the way we expect them to, and maybe we really can't learn our first programming language as a JavaScript. So maybe because it doesn't set itself any rules, and it doesn't really enforce good coding habits. But now we've hopefully developed some good coding habits, and so we can start to foray into JavaScript a little bit. To write JavaScript, similar to opening up a C file with a dot C extension or a PHP file with a dot PHP extension, all we need to do is open up a file with the dot js file extension. We don't need to have any special delimiters like we did in PHP. That sort of angle bracket question mark PHP that we're used to from that, the way we tell our browser that what we have is JavaScript is by including it in an html tag, and we'll see a little bit about how to do that in just a moment. The other thing that makes JavaScript different, though, is that it runs client side. So recall with PHP that we could never really see the PHP that underlined a website. If we ever viewed the page source, we would only see the html that was generated by that PHP. But JavaScript runs client side. Your JavaScript runs on your computer. And that's why you can do things like add blockers. Right? Ad blocking is usually done by killing all of the JavaScript that is running on a particular website. And because it would have to run on your machine client side, you can just stop the JavaScript for running entirely. That also means that when you use a website that includes JavaScript, you have to send the JavaScript source code as part of your http response to the client when they request it. And so you might not want to use JavaScript to do really sensitive things like passing information about users' passwords back and forth, because they're actually going to receive all of the source code, not just the html that is generated, such as would be the case with say PHP. So how do we include JavaScript in our html to start with? Well, similar to CSS, actually, is sort of how we do it here. With CSS we have style tags. And inside of those style tags, we can define a CSS style sheet. Similarly with JavaScript can we open up script tags, another html tag we didn't talk about in our html video, and write JavaScript in between those script tags. Also though, like CSS, we could link in outside CSS files and pull them into our program that way. With CSS we can also, excuse me, with JavaScript we can also specify the source attribute of the script tag to link in JavaScript separately, so you don't have to write it in between script tags, we can link it in using that script tag as well. And just as with the case with CSS where we recommended that it was probably in your best interest to write your CSS in a separate file in case you need to change it, similarly do we recommend that you write your JavaScript in separate files and use the script tags source attribute to tie your JavaScript into your html, your web page. So JavaScript variables, we'll start talking about the syntax here. And we'll go through this kind of quickly, because we've done this in PHP, so this should all be pretty familiar. So variables in JavaScript are very similar to PHP variables. There's no type specifier, and when you introduce a variable, you prefix it with the var keyword. In PHP we would do something like this, dollar sign x. That's how we indicated a variable, but no, we don't mention the type of the variable at all. We would say something like dollar sign x equals 44 in PHP. If we were doing the same thing in JavaScript, we would say var x equals 44. So var is sort of our way of introducing a variable. That's perhaps a bit more intuitive than just dollar sign variable. Again, since there's no data types, we could do this with any data type, strings, anything else would all be var. Conditionals, all of our old friends from C and PHP are still available, so we have if, else if, else, switch and question mark colon. Switch remaining as flexible as it was in PHP, but all of these you're familiar with by now. And similarly with loops are the old favorites of while, do while, and for still available to us. So already we know a lot of the basic JavaScript sort of fundamentals just by virtue of having quite a bit of knowledge now about C and PHP. What about functions in JavaScript? Well, similar to PHP every function is introduced with the function keyword. You say function, and then you begin to define your function. What's a little different about JavaScript, though is the ability to have what's called an anonymous function. So you can define functions that don't have a name. This is something we really haven't seen before. We'll really use the concept of an anonymous function a little later in this video, because it'll make a little more sense in context when we see it in a particular situation that I've crafted here. But let's just take a look at what a simple JavaScript function might look like. So I've gone ahead and opened up my CS50 IDE and I've already run Apache to begin my server running. And I have this file open called Home.html. And I'll zoom in a little bit here. And basically, you can see the Home.html is just a bunch of buttons. And I'm claiming at the top here that this is the JavaScript section materials. So there's a bunch of buttons here, but what do these buttons actually do? Well, we'll head over to my IED, and I have Home.html open here. At the very beginning, here's where I'm linking in all of my JavaScript source files. Right? So I have anonymous.js, clock.js, I'm using the source attribute of the script tag to link in file. So I haven't written any JavaScript directly into this file, but I've pulled in all the JavaScript I've written separately. And if we scroll down here, this should all look somewhat familiar with a little bit of new syntax. We have here header tag for functions and then a button. I have an input that's a type button, and apparently when I click it, I'm going to call some function alert date. And this is how we can sort of mix up a little bit of JavaScript and html. They actually play pretty nicely together, and so apparently when I click on this button, I'm going to call some function alert date. And similarly have I defined behaviors for all of the other buttons that are on that home.html page, which we'll keep returning to during the course of this video. But let's go back up here and take a look at clock.js, which is the JavaScript file that I wrote that has this first function we're going to take a look at. As you can see, I begin my JavaScript function with the keyword function, and I've given this one a name, it's called alert date. Inside of there, I apparently create a new local variable called current date. And I'm going to assign an equal to a new date. And we could get into a lot of detail as to what a date is, and really JavaScript is so big that we can't possibly cover everything in one video. But suffice it to say, this is going to return to me a data item that encapsulates the current date and time. I'm storing that in a variable that I'm apparently going to alert current date. Well, what does alert current date look like? Let's take a look at the file itself back over in the browser window. So again, this is the button that I have tied to, this named function. What's something very different in JavaScript, though? And I click it there and look what it did, it alerted. It popped up this sort of box telling me that the current time is, apparently it's November 4 at 10:43:43 in the morning. And if I click it again, now it's a few seconds later, right? So that's all this function does. When I click this button, it pops up an alert message to me. So there's really not too much to functions that's different from PHP, just a little bit of new syntax that comes with working with JavaScript. Arrays in JavaScript are pretty straightforward. To declare an array, you use the square brackets syntax that we're familiar with from PHP. And similar to PHP, we also can mix data types. So this array, both of these arrays would be perfectly legitimate JavaScript. One that's all integers, and one that is mixed up different data types. But what is an object, what is this notion of an object? Well, if it helps, think about it at first sort of like a C structure or a struct that we've learned about before. In C, a structure contains a number of fields, and maybe we now might start to call these fields properties. But the properties never really stand on their own, right? If I define a structure for a car like this with the following two fields or properties, one an integer for the year of the car and another a 10 character string for the model of the car, I can say something like this, I can declare a new variable of type struct car herbie. And then I can say something like herbie.year equals 1,963, and herbie.model equals Beetle. That's OK. I'm using the fields in the context of the structure, but I could never just say something like this. Right? I can't use the field name independent of the structure. It's sort of a fundamental thing. So fields being fundamental to C structures are very similar to properties being fundamental to JavaScript objects. But what makes them particularly interesting is that objects can also have what are called methods, which are really just a fancy word for functions that are inherent to the object as well. So it's a function that can only be called in the context of an object. Only an object that has defined this function inside of its, if you think about a struct, the function is defined inside those defining curly braces of the structure. So it only means something to the structure. And that's sort of what we're doing here with objects and methods. It's basically like we're defining a function that only makes sense on a particular object, and so we call that a method of the object. And we can never call that function independent of the object, just like we can't say year or model independent of the struct in C. So functional programming paradigms look something like this. Function and then when you pass in the object as a parameter. In an object oriented programming languages, this sort of gets flipped, and we would think about it like this, object.function. So it sort of that dot operator again implying that it's some sort of property or attribute of the object itself. But this is what an object oriented programming language might do to make a function call on a method, again, which is just a special word for a function that is inherent to an object. This is what that syntax might look like. And so we'll start to see some of this in the context of JavaScript. You can also think about an object sort of like an associative array, which we're familiar with from PHP. Remember an associative array allows us to have key value pairs, instead of having indexes 0, one, two, three, and so on like we're used to from C arrays. Associative arrays can map words, such as in the PHP video, we were talking about toppings of pizzas. And so we had an array called pizzas, and we had cheese was a key and $8.99 was the value, and then pepperoni was a key, $9.99 was a value, and so on. And so we can also think about an object sort of similar to an associative array. And so this syntax here would create a new object called herbie with two properties inside of it. Year, which is assigned the value 1963, and model, which is assigned the string Beetle. And notice here that I'm using single quotes in JavaScript. You can use single or double quotes when you're talking about strings. It's just conventionally the case that most times when you're writing JavaScript, you just use single quotes. But I could use double quotes here, and that would be perfectly fine as well. So remember how in PHP we had this notion of a for each loop that would allow us to iterate over all of the key value pairs of an associative array, because we didn't have this ability to iterate through 0, one, two, three, four, and so on? JavaScript has something very similar, but it's not called a for each loop, it's called a for in loops. So if I said to me like this, for var key in object, that's sort of similar to saying for each something as something. But all I'm doing here is iterating through all of the keys of my object. And inside of the curly braces there, I would use object square brackets key to refer to the value at that key location. Alternatively, there's even another approach. If I just only care about the values, I can say for key of object, and just use key inside. So for var key in object, I have to use object square brackets key inside the loop. For var key of object, I can just use key inside the loop, because I'm just specifically talking about the values there. So let's maybe take a look at the difference just to quickly show you the difference between four in and for of with a very specific array, which we have here, week array. So I have to find a new array that I filled with seven strings, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday. And I want to now iterate through this array, printing out certain information. If I use a for in loop to print out information, what do you think I'm going to get? Well, let's take a look. And before we jump over to my browser window, just know that console.log is sort of one way of doing a print F in JavaScript. But what is the console? Well, that's what we're going to go take a look at right now. OK, so we're back here in my browser window, and I'm going to open up my developer tools. Again, I'm just hitting F12 to open up developer tools. And notice that here at the top I've chosen console. So this is the notion of a developer console, and it will allow us to print information out, sort of like the terminal, but as you'll see a little later, we can also type information in to interact with our web page. I'm going to zoom in a little bit here, and I'm gonna now click on for in test. And four in test-- I'm not gonna show you the code for it right now, but you'll get it if you download the source code that is associated with this video-- is just that for in loop that we saw just a second ago on the slide. So I'm gonna click that button, and over here, here's what has printed out in the console, 0,one, two, three, four, five, six. I didn't print out the information inside those array locations, because I used a for in loop. And inside the body of the loop, I just printed out key not object key. But if I now clear my console, and I switch to for of test, and four of test I say I use for of loop instead and print out key, if I click that, now I'm getting the actual elements inside of my object or my array in this case. My array of week days. I printed out Monday, Tuesday, Wednesday. So that's the difference between a for in loop, which prints out just the keys if you just use key inside of the body of the loop, and a for of loop, which prints out the values if you use just key inside the body of the loop. All right, how do we now start to concatenate strings and maybe mix up some variables with interpolation like we were able to do in PHP? Well, we're pretty familiar with this from PHP. This is how we would do it using the dot operator to concatenate strings. In JavaScript, though, we actually use something called the plus operator, which is maybe even a little bit more intuitive, right? We're adding a bunch of strings together. So let's head back over and see what this will print if we're trying to print out all of the information in week array. All right, so under here under string concatenation, I have two options, string building V1 and then string building V2. And we'll see why we need V2 in a second. But I'm gonna click on string building V1, which is the code we were just taking a look at, the console.log with all of the pluses. Let's see if this prints out what we expect. Monday is day number 01 of the week, Tuesday is day number 11 of the week. Well, what I was trying to do there was get it to print out Monday is day number one, Tuesday is day number two. But it seems like I'm always printing out one. Well, why is that? Well, it turns out, take another look at this little snippet of code here. Notice that we're using the plus operator in two different contexts. And so here's where maybe things that we've kind of been saying, oh, it's so great. We don't deal with data types anymore. But here's where the fact that we lose data types can actually be a bit of a problem for us. Now that the plus operator is used to concatenate strings and add numbers together, JavaScript has to make its best guess as to what I want it to do for me. And in this case, it guessed wrong. It just concatenated day, which would be 0, one, two, three, four, five, or six, and then it just concatenated that and then concatenated one. It didn't actually add them together. And so these languages, PHP and JavaScript, that abstracts away this notion of types, you don't have to deal with it anymore. They do still have types under the hood. And we can, in situations like this, leverage that fact by saying something like maybe this, which is telling JavaScript, by the way, treat this as an integer, don't treat it as a string, even though we're mixing together strings and integers here. It's just one of those things that it seems so great in context that we don't have to deal with types anymore, but sometimes you'll run into a situation exactly like this where the fact that you don't have control over types can backfire on you if you're not careful. And so if we pop back over to IDE, I'm going to clear out my console again, and I'm going to click string building version two, which is where I use that parse int function. Now it's printing out information that I'm expecting. Monday's day number one, Tuesday is day number two, and so on. So let's talk about functions again. I promised we would talk about anonymous functions, and now the context for that has finally arrived. So before we do so, let's talk again about arrays for just a second. So arrays are a special case of an object. In fact, everything in JavaScript is actually an object. So functions are a special case of an object, integers are a special case of an object, but arrays specifically have a number of methods. Remember because they're objects, they can have properties and methods. They have a number of methods that can be applied to those objects. There's a method called size, array.size, which will return to you as you might expect the number of elements in your array. array.pop, sort of like our notion of popping off of a stack, if you recall from our stacks video, removes the last element from the array. array.push adds a new element to the end of an array. array.shift is sort of like DQ, it splices out the very first element of an array. But there's also another special method of an array called map. And this is sort of an interesting concept. So what is the idea of a map? You'll actually see this in several other languages, and we're not talking about a sort of cartographers map here, we're talking about a mapping function. In the context we're talking about here, a map is a special operation we can perform on an array to apply a particular function to every element of that array. and so we would say in this case, maybe array.map, and inside of it, we're passing into map is a function that we want to be applied to every single element. So it's sort of analogous to using a loop to iterate over every element and apply a particular function to every element, just JavaScript has this built in notion of a mapping that can be applied. And this is a great context to talk about an anonymous function. So let's say we have this array of integers. It's called nums, and it's got five things in it, one, two, three, four, five. Now I want to map some function on to this array. I want to have a function apply to every element of the array. Well, let's say that what I want to do is just double all of the elements. What I could do is just use a loop for var I equals 0, I is less than or equal to 4, I plus, plus, and then double every single number. But I can also do something like this. I can say nums was formerly one, two, three, four, five, now, though, I would like you to apply a mapping onto this array where I would like you to double every number. And that's exactly what's happening here. But notice what I'm passing in as the argument to map. This is an anonymous function. And notice I haven't given this function a name, I've only given it a parameter list. And so this is an example of an anonymous function. We generally would never call this function outside of the context of map. We're defining it as a parameter to map, and so we don't really need to have a name for it if the only thing that cares about is map and it's defined right there inside of map. And so this is an anonymous function. We have not been able to do this previously. Map some function that accepts one parameter, num, and what that function does is returns num times 2. And so after this mapping has been applied, this is now what nums looks like, two, four, six, eight, 10. And we'll pop over to my browser window and just take a look at this really quickly as well. So I have another button here in my home page called double. And when I click double, and it tells me before it was one, two, three, four, five after two, four, six, eight, 10. And if I go back and click double again, two, four, six, eight, 10. And then after, four, eight, 12, 16, and then 20. And what am I doing in this function? Well, if we just pop over to IDE, and I pull up my anonymous function, here on line seven through 13, I'm doing a little bit fancy work here, but I'm just printing out what's currently in the array. Then on line 16, 17, and 18, there's my map. This is where I'm applying this doubling function to every single element. And then a little further down, I'm just doing the same thing I was doing before, except now I'm printing out the contents of the array afterwards. But all I've done here is just use an anonymous function to map across an entire array. So one more big topic to talk about in JavaScript is the notion of an event. An event is something that just happens when a user interacts with your web page, so maybe they click something, or maybe the page is finished loading, or maybe they've moved their mouse over something, or they've typed something in an input field. All of these things are events that are occurring on our web page. And JavaScript has the capability to support something called an event handler, which is a callback function that responds to an html event. And what's a callback function? Well, it's generally just another name for an anonymous function. It's a function that responds to an event. And this is where we come to the idea of binding certain functions to a particular html attribute. Most html elements have support for an attribute that we didn't talk about in the html video for something like on click or on hover or on load, all of these events that you can then write functions that deal with those events when those events occur on your web page. And so maybe your html looks something like this. And I have two buttons here, button one and button two, and here I have currently defined nothing, but this is where the attribute on click is apparently part of my html tag. So apparently when I define what's going on inside of that attribute, it's going to be some JavaScript function that responds to the event presumably of clicking on button one or button two. What's kind of cool about this is we can write a generic event handler. And this event Handler will create an event object. And the event object will tell us which of the two buttons was clicked. Now how does that work? Well, it might look something like this. So we will first define our buttons to have a response to the callback function that will be called when the button is clicked, we'll call event alert name. And notice in both cases we're passing in this event parameter. So we call this function or when this function is triggered by the event happening, it's going to create this event object and pass it as a parameter to alert name. And that event object is going to contain information about which button was clicked. And how does it do that? Well, it might look something like this. So now in my separate JavaScript file, I might have to find this function alert name, which again accepts that event parameter. And then here is where I'm detecting which button was triggered, var trigger equals event dot source element. What was the source that created this event object that was passed in? Was it button one or was it button two? And then here all I'm doing is printing out trigger.innerhtml. Well, in this case, in this context, trigger.innerhtml is just what is written on the button. It just so happens if we jump back for a second, that would be what's in between those button tags. It will be button one or button two. And let's take a look at how this event handler would look if we had it running in practice. So first of all, you've opened up events.js, which is the JavaScript file where I have defined this function. And as you can see, it's pretty much exactly what we just saw on the slide a second ago. And I will go over to the home page we've been using. And I have here button one and button two. And I'll click on button one. You clicked on button one, if you can see right here in the alert. OK. Click on button two, you clicked on a button two. So both buttons have the same function call, right? They both were alert name event, but this event object that gets created when we click on it tells us which button was clicked. We didn't have to write two separate functions or deal with having to pass any additional information. We're just relying on what JavaScript will do for us, which is to create that sort of event object on our behalf. There's a lot more to JavaScript than what we've covered in this video, but having these fundamental should get you quite a long ways to learning everything you'll need to know about this interesting language. I'm Doug Lloyd. This is CS50.