All right. So, JavaScript. Almost everyone in this room probably has some degree of comfort with it whether it was way back when in SC50 or it's been personal web projects or even if you did a bit of it with this past PHP base project, but for the most part, many of you, even if you have some comfort with JavaScript maybe haven't been taken for granted how the language works and what goes on underneath the hood and what we're going to try to do today is peel back some of the technical layers of what JavaScript is, how it differs from a language like PHP, how can be used not only client side but also server side and then focus very specifically on this framework, notice no JS which is essentially a run time, a program with which you can execute JavaScript code, server side and it's becoming increasingly popular sort of on the same stature this days of probably Ruby and PHP and Python and you'll see that it has some pretty powerful features by way of some of the built-in language constructs. But first, some of the easy stuff just to remind you of how this language works and if you have trouble seeing any of this, just shout out and we will adjust. So, one like in PHP there's no notion of a main function, you just start writing code and you can therefor interpret it top to bottom. In the context of a browser or in something server side we'll see some examples in a bit. Conditions, syntactically equivalent to PHP as well as C, C++ and some other languages so just to give you a sense of how we might structure it, there's just a canonical condition. Boolean expressions, exact same syntactically as you've seen in those same other languages, both for oring and for ending things together. JavaScript has switches, much like PHP and other's do and you're not limited, like in C to integral primitives like chars and ints can actually do other types of values. Loops. So, this is exactly the same and probably a dozen languages, while loops, do while loops and then this trick here. So, this is sort of known as fast enumeration and it's a very clever way of just like in PHP doing for each FU as bar you can similarly, in a JavaScript object, where object is the name of the variable here, say, var i in object and on each iteration of this loop, i is going to be one of the keys from that object. So, if you have an object for a student, and a student has an ID and a name and a house, iteratively i will take of the value of ID and name and house and you can therefor index into object as though it's an array using square bracket notation to get the value of the key ID or name or house and so forth. And contrary to common assumption, JavaScript objects, properties are not necessarily guaranteed to be in the same order, this is also true to PHP so do not assume that things will stay in the same order that you put those key value pairs into an object. How about arrays? There's a couple of ways to write it syntactically but this is probably the most common now just using square bracket notation. So, this is a variable to call numbers containing array of six integers there, here's a simple string and notice what's absent from these examples, what is JavaScript apparently lacking. Yeah. So, there's no notion of typing, certainly not in this context here, but this is indeed a string. So, JavaScript has types and that was indeed an array which is itself a type and each of the elements in that array were of type number as JavaScript calls them. So, it's a loosely typed language and we'll see that JavaScript like PHP has an identity operator and other mechanisms for actually checking what the type of some variable is both for error checking and for other applications. And here's a sample object containing just a ID and a name. And now, notice that we're using curly bracket notation, the indentation and the white space is sort of meaningless and this declares a variable whose name is Rob and whose ID is 1 and the date type is here our number and string respectively. And then this is something slightly different if you've ever done anything with Ajax these days? You probably used an object like this but what's worth noting here? What is syntactically ever so different, just a couple of things between this example which is admittedly smaller and this larger example. So, first in layman's term, what is this? What is the type of staff would you say? OK, it's an array, it's an array of what? Objects. OK, it's an array of objects. And now, focus on just one-- any one of these objects, what's different between this and this? The keys are strings. Yeah. So, the keys are strings, and the keys are actually strings in both cases and this is sort of an Idiotic in my opinion historical design decision whenever you're using JSON, JavaScript Object Notation, which is essentially a transport format for sending data typically across the network between client and server, you need to remember that this is not actually valid JSON and this is one of these FYIs unless you ever bang your head against the wall for several minutes for no good reason, it's not valid JSON because the keys are not actually quoted. JSON idiotically requires that the keys not only be quoted, but that they be doubly quoted, single quotes do not suffice. So, stupid little thing and more of a fun fact for today's purposes but this too would be valid JavaScript it's just not-- the converse is not true. All right. So, we'll see plenty more of that. All right. So, that's JavaScript syntactically probably pretty familiar, any of you who have never used JavaScript before it's not a huge leap from PHP or most any procedural language that you might have used. So, today we'll focus on the interesting aspects of JavaScript particularly in the context of no JS but not exclusively because up until now you've probably, if you used Javascript, used it inside of a browser. So, no JS is an environment then in a little bit is going to allow us to access JavaScript code client-- server side but first, let's take a look at something that's a little more client side. So, I've gone in and this is linked on the courses website, if you want to play along, there are two subdirectories in today's Zip of called source studs zip on the website and these are just a few examples reminiscing of things you might have seen before and I sort of built them up from simplest to slightly more complicated to tease out some of the features of JavaScript. So, let's go ahead and take a look for instance at this. So, sadly the blink tag was killed off several years ago as the way have got prettier and prettier and the blink tag was literally open bracket blink close bracket and it sort of no longer with us. But, we can still resurrect this idea of a tag by just kind of thinking about it logically, how do you go about making something like this blink intuitively? Assuming you know a little bit of JavaScript and or CSS at this point, it's OK if you don't. Set a time out and hide it then after I'll tag it out and show it again. Yeah, perfect. This is sort of programming 101, how would you achieve a visual effect like this? Well, you somehow have to show something and then hide something, show something, hide something and as Jonathan proposes using some kind of time out, some kind of schedule you can do this repeatedly without needing to use a loop or something like that. So, let me go into blink-0.html and let me shrink the font a little bit so that more of this fits. And let's take a look at what's going on here. So, first of all, notice that the body of this page is super simple, inside of the body of the page is just a div. I've arbitrarily given an ID of greeting and that could be anything so long as it's unique and then I just have some simple text, hello world. So, if I now scroll up, notice some fluffy styling. So, I say, sharp greeting, which as you know in CSS just means uniquely identify the element with an idea of greeting, font size is going arbitrarily be this, margin and text align. So, uninteresting aesthetic details to roughly center the text. So, the interesting part is in the script tag up here which I happen to put inside of the head of the page. So, we'll-- you can do this in any number of ways and we'll see a few iterations of this same program but let's start from the top. So, I've declared a function called blink and apparently it uses this built-in DOM method called getElementById which is perhaps one of the more powerful methods that you get out of the box with JavaScript looking for "greeting" doesn't have to be double quotes like it was in HTML is either is fine so long as you are stylistically consistent these days I dare say many people use Java, single quotes in JavaScript, double quotes in HTML but it doesn't really matter so long as you're consistent. So, here if you're not familiar, you can actually access with JavaScript CSS properties on elements. So, notice that I've declared a variable called div and stored inside of that variable, a reference to whatever that DOM element is. So, if you think back to CS50 or any class in which you thought about tree structures and DOM, Document Object Model, this is just a reference to a node in a tree, that represents this page and if div.style.visibility property equals, equals, equals, hidden, then I just want a toggle it as Jonathan proposed otherwise I want to toggle it over to hidden. Now, as in the side, why the triple equals there? Or what is that versus double equals? Strict equivalent. Sorry. Strict equivalent. Strict equivalent. So, it's the identity operators where by you're checking not only the value of the variable as an equal, equal sense but also the type of it. So, even though we haven't specified this far any data types for any variables in this or any of the slides, there is a type associated with that string hidden with that value, hidden and that is of course string. So, in this case, it doesn't really matter because there's no way that we're going to conflate a string of "hidden" with some other value but this is often a good habit I would say to get into using the equal, equal, equal sign is generally a good thing. It will make your code more robust both in PHP but and in JavaScript because you'll run into occasionally corner cases where the value might be zero that you're checking for and zero can be conflated with false or could be no and as in PHP, Javascript too can have multiple falsely values where by zero and false and null and undefined can all resolve implicitly to false. But if you're really wanting to check for particular value like zero, the number, or false the Boolean then you have to use this identity operator. So, it could happen to get into anyway even though here, it's sort of meaningless because we know we're checking for a string value and it's not going to be anything else. So, here's the magic then, if I scroll down to this line here, apparently, built into the window object and this is a feature of a browser you could access to this super global object called Window, inside of that is some functionality, if piece of which is set interval and it takes apparently what kinds of arguments? Yeah. Function call and a time. Good. So, a function call and a time and so particularly a reference to a function, a pointer to a function in a sense and that's the function that's going to get executed every number of milliseconds and in this case, it's every 500 milliseconds. So, it's a way of inducing effectively and infinite loop without using iteration but instead telling JavaScript to the engine inside of the browser to do this every 500 milliseconds or is close to 500 milliseconds as it can, it turns out that underneath the hood, there's what's called an event loop and we'll come back to this in the context of node JS that just constantly kind of sitting there, spinning, waiting for work to be done and as soon as it realize, 500 milliseconds have passed blink will get called again and again and again is alongside of any other work that needs to get done. So, what can we improve here? Well, let me open up blink-1.html and demonstrate the blink-1.html as aesthetically perfectly identical. So, what could we improve here? Well, notice that it was kind of useless to define a function called Blink because how many in how many places did I call the function blink? Just once. So, one. So, it wasn't bad, in fact it's probably pretty straight forward. I defined a function blink, I call a function blink by way of this parameter, but technically, there was not reason for it and a common paradigm in JavaScript is to actually make use of lambda functions as you may recall from 51 or anonymous functions where if you don't need a name for a function, if you're only calling it certainly in one place, why bother cluttering your code, cluttering the programmers mind and your name space really with symbols that you don't really need to care about. And so, in this version here, notice that I'm calling window.SetInterval directly at the very top of my script tag then I'm passing in a nameless function that takes no arguments and that's perfectly fine and then the body of that function it appears is identical to what it was before and the only syntactic difference now is down here next to the 500. I'm closing the body of the function and then I'm saying execute that previous code, every 500 milliseconds. So, very marginal change but a step toward what's probably a more elegant implementation of this. So, let's take this one step further if I now go into blink two, you'll see a common library, the effect of which is going to be completely inconsequential aesthetically but if we go into version two here, notice that at the top of my head, I've included the latest version of JQuery. And then, down here, I just cleaned up the code a little bit, it's not going to be a fun world to continue using native DOM functions and sort of raw JavaScript. In fact, JQuery as you may know has become so popular that most people just conflict jQuery with JavaScript but really just a supper useful library written by a fellow named John Resig and since others that have just makes a lot of tedious things in JavaScript easier and more succinct. So, in this case here what's going on? So, I have this appearance of a dollar sign, more on that in just a moment, then this is a CSS selector. So, it's very similar in spirit to what I did before, but this time, I'm literally using the hash tag to indicate a unique identifier called greeting and then apparently .css is a method built in to whatever object is that I just created and I'm checking the value of the visibility key. And if the value of that key equals, equals, equals, hidden, then I'm going to toggle it and I'm going to toggle it this time by using the same method which apparently is overloaded in the sense that it has two different signatures, one with one argument and one with two arguments, the second of which is the setter, the former of which is a getter so to speak. And if curious and if you'd never actually looked at this, if we go to jquery.css hopefully the top hit is indeed this and you can see a more formal explanation that we just use this, .css with property name and then the setter is dot CSS with a property name and a value. So, marginally cleaner, but notice the sort of pattern here with each iteration of this code, we're sort of making it tighter and tighter and tighter and there say better designs since we are using someone else's code that's eliminated some of the complexity. So, now let's make this even simpler. And in fact, if I remove all the quotes you'll see just all the comment you'll see how simple this has gotten. The one difference here of course is that I'm using a toggle method which also comes built in to jQuery and that's just because someone else wrote the code that actually toggles the visibility setting of any DOM element that you send it. So, better and better. And so, this is a pattern, even though this is a supper simple example and sort of stupid net effect which is a blinking piece of text, it's that kind of thought process that you should think-- be thinking about not necessarily the very first passive writing something for the forthcoming project but certainly as you iterate with your adviser or with me and your team meetings or you just review your teammates code about tightening things up, right? After all, they're less-- a fewer lines of code you ultimately have in theory the fewer bugs you are likely to be inviting because there are simply less code to mess up with. All right. So, a couple of takeaways. Lambda functions, anonymous functions, many of which you have seen before and then also just tightening things up with a library like jQuery in this particular case. All right. Any questions? Let's do one other client side aspect here, in form zero we have this net effect. Super simple form and apparently if I try to click register here, initially it tells me you are registered, well, not really. Well, why is that? Well, here's form-0.html very little code, no JavaScript whatsoever and it's completely a fake sort of form because the action value is registered.html which means no matter what I type into this form, where is it going to be sent on the server? Yeah. So, to registered.html which is clearly an HTML file which is therefore static file which has no means of taking user input assuming there's no JavaScript code embedded in it that's looking in the URL so this is completely a NOOP and that nothing is going to happen with a submitted data, but you can see the structure of a fairly simple HTML5 form that has a few password, a few input types. So, let's actually now add some error checking and see how we might improve this. So, here is sort of a poor man's way of implementing this and it's sort of a nasty chunk of code. So, first let's scroll down to the bottom to see what's the same and what's different. The only thing different now between this and the previous version is that I've given the form and ID of "registration" could have been anything I want but its meant to be uniquely identifiable even that's not strictly necessary because if a page only has one form surely I could find it with one of jQuery's selector methods. But this way just makes it more deterministic. So, if I go up now to my script tag, notice the following, window.onload equals an anonymous function. So, what is this doing? So, you may recall that in client-side programming-- JavaScript rather HTML pages have various events associated with elements, clicking and submitting and focusing and blurring and other such events that could happen as a user typically interacts with the page, window.onload does what it says. On the windows entire loading so once all images have been downloaded once all files have been downloaded and once the page has been loaded, do the following code, and notice if I switch to the bottom of this method, notice that there are no parenthesis after the curly brace which is to say that I'm not executing this function up here now, the browser is going to execute it for me when it has determined that the page has loaded. So, let's see what we've done, document.getElementById registration so that just gives me a reference to the node in the tree that's of has an ID of registration. And now, I'm going to register another event handler by doing form.onsubmit gets this anonymous function which means the following code should execute whenever that form is submitted. Now, most of this is just sort of boring logic. So, if the value of the email field in the form is "nothing" then you must provide your email address, you yell at the user with an alert and then return false. And then I have a bunch of other checks, the checks for the password, the checks if the passwords are the same, the checks if the agreement check box is checked or not and I just yell at the user if any of those tests actually fail. And so, here is an example even though it's a little contrived here the fact that I'm using equals, equals, equals, means that the user cannot try to trick me by typing in what value. Or rather I'm truly checking for the presence of the empty string, the user has not typed anything yet. If the user typed in literally zero, "zero" potentially could be confused with the empty string. And I say it's sort of meaningless here because obviously even zero is not an email address. But if this was a more generic field like a text field or a name or a description or something you want to value for and it's not necessarily syntactically have to be an email address, the user could type something like zero and again corner case but that's why typically checking types is a useful thing. You're truly checking for the user having typed nothing into that field. So, what happens if none of those tests fail, well, returning true inside of an event handler like onsubmit just means let the original behavior actually propagate and therefore the form will get submitted. And that's why when I finally clicked submit before I got through to register.html and if I do that now, notice, I get yelled at if I don't provide an email address and I can type in malan@harvard.edu, crimson [phonetic], crimson, checking the box, and now register and it tells me, again, you are registered or not really. All right. So, let's clean this up just a little bit and then transition to the new newer server side stuff. So, if I go into form-2.html, notice a few things. So, one, I brought jQuery back into the mix so there again is this dollar sign and now I'm using some jQuery methods. So, first, what is it about the dollar sign that's so special here? What is the dollar sign laced throughout most any jQuery code? Yeah. [ Inaudible Remark ] OK. So, the dollar sign function goes through the DOM looking for something with this particular CSS selector. So, true but almost too precise. That is what happens when you pass in a string as in this case, but you don't always have to pass in a string. In fact, case in point, the very first line here is this is not a CSS selector, I'm passing in a Lambda function. So, more generally-- so, good answer but too precise. More generally, what is dollar sign represent? Just jQuery. Yeah. So, just jQuery or it's just a function that some guy years ago wrote and other people have since enhanced that literally by default is called-- oops, is called jQuery. It just-- it turns out unlike a lot of languages dollar sign is a perfectly valid symbol to use in a variable's name whereas in PHP dollar sign obviously has special meaning but in JavaScript like in some languages, dollar sign and underscore and other such special characters totally legit to use in your own symbol names for variables. So, someone just decided that, you know what? It's going to be pretty tedious to make the whole world type jQuery all the time, let me sort of plant a stake in the ground and say, "This library will use dollar sign." And in fact, this does raise the risk that someone else presumptuously is going to use the dollar sign for his or her library but there's ways to sort of insure that when you use the dollar sign it maps to jQuery because you can test if it's already been assigned to something else essentially. All right. So, that's all that is, there's no magic. It's just a sexy looking piece of syntax that is nice and quick and easy to type. So, what happens when you type dollar sign open paren and then an anonymous function. Well, turns out that this is actually shorthand notation for document dot ready open paren. So, as Cynthia noticed earlier we already found one corner case. If you just pass in the lambda function, the effect of the dollar sign is a little different. In fact, what's really happening is that it's equivalent to this, passing in a reference to the global document object that is global just like the window object is that gives you some special functionality that affects the whole page or browser and it turns out that document when you wrap it with jQuery, jQuery essentially realizes, oh, this is a reference to that special document object, let me now register an event handler called ready which is not native JavaScript or DOM related. Ready is a jQuery thing that says when the page has loaded all of the HTML elements but not necessarily loaded, all of the CSS and images and JavaScript files and flash files and the likes. So, it's a step before on load then go ahead and execute the following. And the upside of using on ready means is that you can, you know, that all of the elements in your DOM, all of the uniquely identified things with IDs, they exist even if the page, its contents are still loading and loading and you have some broken icons for a moment or white page in the background. Yeah. What would happen if [inaudible]? Perfect example, a perfect question. So, let's see if we can simulate this right now. So, let me go ahead and delete this two lines up here and then without bothering to fix the indentation, let me go ahead and delete this down here-- oops, this one down here. And now, let me go over to the page, go to form-2.html and type in Register, nothing seemed to happen, let's say, why was that, let's go ahead and open up Chrome's inspector, open up the Console just to see if anything happens here, now, register, still nothing. So, the code is syntactically fine so I'm not seeing any red error messages, but what clearly is not happening? None of my code is right, it's not working so none of my codes seems to be executing, so why is this? Well, JavaScript and browsers more generally execute the contents of a web page, top to bottom, left to right. And the problem is that because the top of this page has HTML then head then script then another script, this is going to get executed before what is even ready, or even exists in the tree representation of the page. The form itself, not even the body exists at this point. So, jQuery is smart enough with it's error checking that if there is no element with the unique ID of registration, it's not going to bail out on you and just trigger some console error and break the whole page, it's going to silently ignore you, but the reason that none of this code ever executes is because when you have registered this submit handler, there was no element to attach it to. So, it's sort of a no op there. So, by specifying instead, wait until the age has loaded if we did the window.onload thing which is sort of the old school way of doing it or the sexier jQuery way like this, we can tell it wait until all of those HTML tags have been parsed so that even if the images haven't loaded, at least that node is in the tree, then JQuery can be ensure that everything is there. Yeah. [ Inaudible Remark ] Yes, good, yes absolutely. So, the other solution to this, if you didn't use this or didn't remember that this existed, you could absolutely move all of this to the bottom of the web page, inside of the body still but below the form and that would also solve this problem. It's just typically considered bad practice. It's a little messy and sloppy specially if you keep jamming everything to the bottom of the page, especially when I'm keeping things simple by putting all of my code inside of the HTML page when of course you can certainly get into the habit of factoring it out to a separate file at which point it's just nice to centralize the files in the head. Except there is a price you pay by putting JavaScript another assets like CSS files in the head of the page, what's a risk that you run? Slower page loading. Slower page loading, why? Because we're trying to load all the libraries before [inaudible]. Exactly because browsers read the code top to bottom, left to right if Google analytics are slow or the jQuery CDN is slow or the Facebook API is slow and that file just hangs potentially depending on how you loaded that file, the whole page could appear to hang. And if you see this a lot frankly on websites they have a lot of low quality advertisements on them, we're just one slow or downed website could hang a page for some indefinite number of seconds until finally the browser hopefully times out on that and then shows you the rest of the page. So, if you've ever used like the Facebook, like button, in your web page, let me see if I can find this without having to log in here. So, if you go to the Facebook's like button and click a get code, damn it, lets see if we can find the example, surely someone had posted this. [ Pause ] I'll give up in a few seconds if we don't see this. Facebook asynch-- OK. So, this is the code and unless they've changed it recently that Facebook actually recommends that you use to load their library and actually propose that you put this in the body of your page. So, Facebook advises you create a sort of stupid DIV that just has unique ID like this, then have a script tag and all of this complexity essentially does the following and they don't use any JQuery because they don't want to assume any other dependencies, let me move this over just a bit. So, notice they have an anonymous function here, more on that in just a moment, they then use document.createElement, they're creating a DOM element, this is like malloc so to speak where the tag is of type script, it's then specifying that the async attribute of that tag is going to be true then you go ahead and figure out what the URL of Facebook's JavaScript should be and this is just the fancy way of checking should it be HGP or HDPS. And then finally, you notice what Facebook does, they get the DOM node that has an ID of Facebook root which is what they told you to put into the page and then they append the child so the effect of all of this is to sort of dynamically inject a new script tag into your page as a child of the DIV that you inserted there so that the rest of the page loads happily and then this code actually gets loaded asynchronously. So, essentially after the fact and I deferred mention of the anonymous function, what's this funky syntax referring to here when I have not only function open paren, close paren and then curly braces, why the open paren here and then the open close, close paren there, what's that doing? [Inaudible] defining and then executing? Exactly, it's defining a function which is anonymous but merely defining a function, of course does not execute a function until you call it by name, but of course this is an anonymous function so you can't call it by name but you can in JavaScript execute an anonymous function just by encapsulating the whole thing in parenthesis as we've done with this paren and this paren here and then a fixing to the end of the function open paren, close paren, if you don't want to pass it any arguments. But this seems kind of stupid, like why this additional syntactic complexity that most people didn't seem to recognize, what's the value of wrapping those three lines of code in an anonymous function in this way. Yeah. To avoid overwriting a valuable in the [inaudible]. Exactly, to avoid overwriting a variable in the existing page, right? Facebook is somewhat presumptuously decided, they're going to use the variable E, it's quite likely that you or anyone using the Facebook like button or whatever other social plug in has a variable somewhere called E. So, by encapsulating all of their code inside of this anonymous function, they essentially have their own scope that doesn't risk clobbering any existing variables. So, this too is actually a very common paradigm, especially when writing a library code or when you yourself don't want to clutter your name space with other variables you want the value to live and die once you exit that block of code, this is a nice technique in JavaScript. All right. So, then back to this example here, all we've done in the end with this example is just cleaned up the code. So, it's still got a whole bunch of switches, a whole bunch of conditions here, but notice a bit of syntax, this accesses the DOM node with the unique ID registration, the space means look now for a descendant of that node, find it if it's of type input and then even if you haven't seen this before, you might know that this just means find it with the input tag, the input elements that has an attribute of name with a value of email, and then let me wave my hand at some of the rest is not all that stimulating but really just jQuery syntax for the same operations. All right. But what's not so important here is the browser side stuff but rather the fact that we had cleaner and cleaner ways of actually making that code work. All right. Any questions? [ Inaudible Remark ] OK. Now the fun part. So, node.js Why? Who cares? What do you know of it today? Node.js, why? Henry [assumed spelling]. [ Inaudible Remark ] Battery reset? What-- this is a perfect cliff hanger for the latter half of today. Why don't we go and take a 5 minute break here, there's a half candy machine there if you would like some candy without putting a quarter in.