>> [MUSIC PLAYING]
>> DAVID MALAN: This is CS50.
This is the start of week nine.
And this is what would have been Mr. Boole's 200th birthday.
So this is the fellows to whom we've alluded
quite some times about using Boolean variables true and false,
1 and 0 and such.
And this was Google's tribute to him today.
He would have turned 200.
So if you'd like to join us for CS50 lunch,
take a look at the link on the course's website.
And such faces and friends as these await you here in Cambridge.
Faces like these await you in New Haven.
And, in fact, Ken in New Haven kindly made
what's called an animated GIF of Eli here at a recent lunch-- a GIF is yet
another graphical file format, with which you're familiar-- that
looks a little something like this.
So just a sequence of-- OK.
No one here in Cambridge is laughing.
But in New Haven, this is really funny, right?
All right.
>> So do join us there.
Here at Harvard, specifically, this Wednesday,
if you're a sophomore or freshman even-- or even junior-- thinking of making
a switch into computer science, know that there'll
be a CS advising fair this Wednesday, shortly after class
at 4:00 PM in the computer science building Maxwell Dworkin.
We'll put this on the course's website by tomorrow, as well.
Donuts, I'm told, will be served.
>> All right.
So funny story-- I was poking around on the internet,
and I found some old archives of my former website.
And it turns out-- around this time, it seems very timely
since I gather that the UC elections are about to gear up again.
So I ran for UC, lost miserably.
And maybe this was in part why.
So this was my website at the time.
For some reason, I thought it was a good idea, before telling people
what my platform was and why they should vote for me, that they have
to click to enter to find out that information, which in retrospect is
kind of creepy.
I don't really know what that was.
>> But it certainly didn't help my campaign.
I also found that by senior year-- I had this Muppet calendar.
Muppets were kind of in vogue back then.
Or maybe they weren't.
I had a Muppet calendar back then.
And I thought it'd be cool to name my computer on Harvard's network
frogman.student.harvard.edu.
At the time, we all had uniquely identifiable host names.
And you could choose some vanity name instead of your own name.
And I went with frogman for some reason.
>> And then I started-- I spent a lot of time clicking through these links
this morning.
And this was my about page, which now kind of seems adorable.
But it also testifies to just how far technology has come.
I mean, back in the day, a 486 was something.
These days, it's super, super, super slow and well less
than you might have in your own pockets these days.
There's more on there that was even more embarrassing.
So I'll leave it at that.
But that was my first foray into web-- oh, no.
That wasn't.
My first real foray into web programming was this site, which I just forgot.
At some point, I learned how to make repetitive background images.
And so I found this tiling effective, like hockey player, football, and golf
ball, or whatever that is for the Frosh IMs website.
And this was actually, genuinely the first web-based project I took on--
I think maybe sophomore year, junior year--
after taking CS50 and CS51, one of the common follow-on classes.
I noticed in looking through the archives
that one of my successors and friends, Lee, kind of changed
the copyright to himself.
But this was indeed something that I should own the embarrassment to.
But at the time, this was the first website,
as I said a few weeks ago, by which freshman could
register for intramural sports here.
And so it turns out that background images
like that are not such a good idea.
But the web was new, and we were all experimenting.
And this is what I apparently did at the time.
All right.
So without further ado, we switch gears today to give you, really,
the final piece that you might find especially useful for final projects
but also that will start to make the whole world wide web
feel a little bit more understandable.
Indeed, we're going to introduce one more programming language
called JavaScript that's similar and different in different ways
from languages we've looked at thus far.
>> So C, recall, is this compiled language.
You've got to run it through a compiler.
You get source code to object code, or zeroes and ones.
And those are zeroes and ones that your CPU, Central Processing Unit,
actually understand.
PHP, by contrast, isn't a compiled language.
It's a what?
It's an interpreted language.
So there's some program called an interpreter that
has to read it-- top to bottom, left to right--
and figure out what all of your syntax does and means,
whether it's a loop or a condition or any other number of programming
constructs.
So that's an interpreted language.
>> Then we introduced HTML.
And HTML's not even a programming language.
We'd call it what?
A markup language, which is just a sort of fancy way of saying it
doesn't have programming constructs like we saw even back in the day of Scratch.
There are no loops.
There are no conditions.
It really is a language about marking up your data
and formatting it or structuring it in some way.
>> CSS, meanwhile, similarly not a programming language.
It's even more aesthetically oriented.
And it allows you to sort of fine-tune things like font size and colors
and placement and all of that.
Then we had
>> SQL.
So SQL is indeed a programming language in some sense,
albeit tailored specifically to databases.
But even though we only introduce you to select and insert and delete and update
and a couple of others, turns out you can actually
write functions or procedures, as they're
called, in SQL that look and act quite like PHP and C functions.
So know that those exist.
But we don't even bother with them as we just scratch the surface here.
And then JavaScript, the last of our languages formally introduced.
So JavaScript, too, is an interpreted language.
And those familiar, do you want to distinguish it
with some characteristic from both C and PHP?
What makes it different?
>> AUDIENCE: It's not compiled.
>> DAVID MALAN: Say again?
>> AUDIENCE: It's not compiled.
>> DAVID MALAN: It's not compiled.
So it, too, is interpreted.
So it's not compiled.
But that makes it a little like PHP.
But it's still different from PHP in some striking way,
at least in the way we'll use it.
Yeah?
>> AUDIENCE: It runs client-side.
>> DAVID MALAN: It runs client-side, usually.
That's indeed the distinguishing characteristic for us right now.
C was server-side in the sense that we did everything in CS50 IDE.
PHP thus far has been server-side insofar
as it, too, gets interpreted-- not compiled, but interpreted--
inside CS50 IDE, which of course is just a server or servers in the cloud.
>> But JavaScript, even though you you're going
to start writing it for, say, pset eight and maybe final projects-- you're
going to right it in CS50 IDE and save it
in files within CS50 IDE, CS50 IDE and, in turn, the cloud servers
on which it's hosted, are not going to interpret or execute your code.
Rather, it's going to be sent in unaltered form down to the browser.
And it's then going to be IE or Chrome or Firefox or Safari
or whatever that actually interprets it, top to bottom, left to right.
So the key distinguishing characteristic for today
is that JavaScript is client-side and PHP, for instance,
has been server-side.
Now, this has interesting implications for, like, intellectual property
and who can actually see your code.
And indeed, you can go on the web and see most
any code that someone has written in JavaScript.
Sometimes it's readable, sometimes it's obfuscated.
But more on that in due time.
>> So JavaScript, nicely enough, is super similar, syntactically, to C.
And much like PHP, there's no main function.
If you want to start writing JavaScript code, as you'll see today,
you just start writing it.
But it is, you'll see, particularly useful in the context of web browsers.
However, my little disclaimer-- usually earlier--
was to say that you can increasingly today use JavaScript server-side
using a fancy framework called Node.js that some of CS50's own applications
are written in.
Check 50 actually uses Node.js.
But we're going to focus on JavaScript client-side here on out.
>> So here is a set of conditions in PHP.
Sorry, in-- actually, that statement, too is correct.
Here is also a set of conditions in JavaScript.
Syntactically, it is identical to C and to PHP.
Mr. Boole's expressions are, similarly, syntactically
identical to both C and PHP.
We also have switches in JavaScript that look identical.
We have for loops that are structured identically,
while loops, do while loops.
>> This one's a little different.
PHP had the for each construct that you might be using
or will use in pset seven, perhaps.
JavaScript has this special version of for where you literally say something
like for variable key in object, which is a very succinct way of saying,
if I've got an object-- and we'll talk about these again in a moment--
and I want to iterate over all of the key value pairs inside,
I don't have to figure out how to numerically index them with zero, one,
two, three.
>> I can literally say this.
And on each iteration, JavaScript for me will update the variable key
to be the first key, then the next key, then the next key, then the next key,
and so forth.
And I can get at its value by treating an object in JavaScript, as we'll see,
as though it's an associative array in PHP.
Indeed, if you finally wrapped your mind around what an associative array is
in PHP, you can think of it for now as identical to an object in JavaScript.
But that's a bit of an oversimplification.
>> Arrays look, nicely enough, identical to PHP except for one character.
There's one thing missing here that we did see last week with PHP.
What's omitted?
Yeah?
No dollar sign.
So we're back to a more normal world where
variables don't have dollar signs.
But you do prefix them with var, typically.
And var means variable.
And much like PHP is loosely typed-- whereby there are types,
there are numbers and strings and floats and so forth--
JavaScript similarly has types.
But it's loosely typed in that we the programmers don't have to specify them.
We just have to be aware that different types exist.
>> Variables, meanwhile-- here's how we might declare "hello, world"
as a string.
Notice it's identical to PHP but no dollar sign.
And this is something we'll start seeing more today,
whereby you have an object with keys and values.
And if you want to try to infer from last week--
the syntax is a little different.
But a little sanity check-- how many keys does this object seem to have?
So I see four.
I see two.
>> So it's actually two.
So this is a collection of two key-value pairs.
The key is symbol whose value is FB.
The key is price whose value is 101.53.
So those are two key-value pairs.
And remember, PHP-- and this is again just sort of syntactic difference.
It's not all that intellectually interesting.
PHP might have written this same thing as follows-- quote, equals.
And I change these to square brackets.
And then I change this to a quoted word, "price."
And then I don't use a colon.
What did I use last week?
Yeah, the equal sign arrow funky notation.
>> And then I did the same thing here.
Same thing here.
And that's all.
So it's fine if this hasn't really sunk in to memory just
yet because it's really intellectually uninteresting.
It's just syntactic differences.
But the ideas are exactly the same.
Inside of this variable quote in JavaScript
is a collection of key-value pairs, one of which is symbol, one of which
is price.
And I can get at those values with the following syntax.
Just like in PHP, I could do something like-- let
me make this box a little bigger.
Just like in PHP, I could make this-- oh, dammit.
Come on.
>> Just like in PHP-- OK, we'll just use the presenter notes.
Just like in PHP, I can do $quote$quote["symbol"],
and this will get me the value of "symbol."
In JavaScript, it's going to be identical, whereby I can just do this.
The only thing that's missing is the dollar sign.
>> So nicely enough, then, there's not all that much new syntax.
So what today we focus on, really, is some of the ideas and the applications.
And the first such application that you might
have seen if you dived into pset seven already is this syntax.
So in pset seven, if you've seen or not seen it yet,
know that there's a file that we give you called config.json-- JavaScript
Object Notation.
Why?
We wanted to be able to provide you with a template with some key-value pairs.
We wanted to be able to give you a list of the host, the name of the server.
We wanted to give you a placeholder for your username
and a placeholder for your password.
If you're not seeing this yet, not to worry.
More on this in pset seven [? spec. ?] And then,
obviously, we want you to fill in the to-dos
because when you log into CS50 IDE, each of you
have your own username and password.
>> So we could've used a half a dozen or more different file formats.
We could have used a .txt file.
We could used a CSV file.
We could've used an INI file, an XML file,
a whole bunch more acronyms that you might not have ever heard.
It's kind of arbitrary at the end of the day.
But super popular these days is a text format called JSON-- JavaScript Object
Notation-- that looks like this.
It's a little cryptic, but notice the patterns.
You start with an open curly brace, and you end with the same.
Inside of that is something.
It's a key-value pair.
So this is an object that I'm looking at on the screen here
that has one key, which has one value.
And just inferring based on the previous pattern, what's the key here?
Database, the thing to the left of the colon.
>> Now, the value happens to be a multiple lines this time.
But the value starts with a curly brace and ends with a curly brace.
So what would you propose is the type of the value of database?
A dictionary or, just more succinctly, an object.
Right?
This is kind of a data structure that can use other structures within itself.
So if this whole thing we're calling an object-- and an object
is just a bunch of key-value pairs-- the value of database itself is an object.
The value of database has a whole bunch of key value pairs, the first of which
is host, then name, then username, then password,
each of whose values, meanwhile, it's just a boring string in double quotes.
>> So even if that's not super clear just yet,
know that this is just a standard, fairly boring way
of storing data in a standard format.
But the common mistakes you might make, even in pset seven,
are little stupid things, like if you accidentally omit the comma there.
That's going to result in the file not necessarily being readable.
If you accidentally omit things like the quotes, it's not going to be readable.
So it's a pretty nitpicky file format, but it's one that's super common.
And we happen to use it, even though you don't use any JavaScript otherwise,
in pset seven.
>> All right.
So remember this picture.
We talked about, in HTML, that the code might look like this.
This is the HyperText Markup Language [INAUDIBLE] for just "hello, world."
But then we proposed a while back that if it helps,
you might want to start thinking about this already as a tree.
In fact, the indentation that we use just for readability's sake
or for style's sake on the left can kind of
be translated into this tree, where you have some special root node that we'll
generically called document, below which is the root HTML element or tag, HTML,
which then has two children, head and body.
>> And then in turn, head has a title.
And title has a text value.
And body similarly has a text value.
So if you're comfortable saying that yes, you could take this HTML
and draw a picture like this, the right-hand side
is a nice mental model because now that we have JavaScript, a programming
language that browsers can execute and interpret for you,
it turns out that what we're about to do in code
is start to manipulate this tree structure in memory.
We don't have to build the tree in memory.
We don't have to do sort of pset-five-style data structure
complexity.
The browser, nicely enough, upon interpreting HTML top to bottom,
left or right, is literally going to hand us the equivalent of a pointer
to that entire tree for free.
It does all of the hard work.
That's what Mozilla and Apple and others have done for us.
>> And with JavaScript are we going to be able to control and change and do
interesting things to that tree, otherwise known
as a DOM or Document Object Model.
What kinds of things?
Well, it turns out that in JavaScript, there's
this laundry list of events that can take place.
And we haven't really used that word since week zero and pset
zero when we talked about Scratch.
Most of you probably didn't use an event in your Scratch project.
But you might recall the simple Marco Polo
example, where we had two sprites, one of whom said, Marco.
The other of whom then, upon listening and hearing that event, said, Polo.
If not, feel free to look back that far back.
>> But this is just to say, and you can kind of
infer from the names of these things, JavaScript, it turns out,
is going to give us a way to listen for mouse going down or mouse going up
or key going down or key going up or onsubmit onselect
or onresizing something.
In other words, any physical action that a human can take with a browser
that you do every day, you can write code for that listens for those events
and then does something appropriate.
>> For instance, if you use Google Maps, what happens if you click and move
the mouse, typically?
If you click and drag?
Yeah?
Exactly.
The map starts to move.
So you can sort of see what's over here, what's over there.
And how does Google implement that?
Well, presumably, they're using a couple of these event
listeners, one that says, listen for on mouse
down-- so when the user physically pushes his trackpad or his or her mouse
down.
And then we're looking for something like movement
or some other event that allows us to capture drag.
And in fact, drag is similarly in this dot dot dot list of possible options.
>> So this is going to be a powerful way to start responding to the user
even before he or she actually clicks something explicit like submit.
But we're going to introduce a couple topics to get there.
But first, let's transition to some actual code.
So I'm going to go ahead and open up dom-0,
which is a very simple example here that if I zoom in simply
has this input here for me.
And I'm going to go ahead and type in "David" for my name and click Submit.
>> And then, albeit sort of cheaply, I have this prompt that pops up that says,
"hello, David!"
So this is kind of like our "hello, world"
that we did awhile back in C and even in PHP because I've dynamically
outputted my name.
I can do someone else's name here.
I could simply change this to, like, Hannah, click Submit.
And indeed, the little pop-up changes.
>> Now, pop-ups are one of the most abused features of the web.
And in fact, back in the day pop-up blockers
came into vogue because you would go to some website--
perhaps a questionable place-- that would then suddenly
start peppering your screen with a whole bunch of pop-ups.
And so this ability to pop up windows in front of the user
has not been particularly well-received by humanity.
So that's why you see this prevent thing,
which just makes this whole thing ugly.
So we're going to need a better way to prompt the user.
But for now, that seems to work.
So just intuitively, what seems to be happening here?
I go ahead and click Submit, and then something's happening, clearly.
But what's not happening that did happen last week any time I clicked Submit?
What didn't happen on the screen?
Sorry?
Reload.
The URL didn't change at all.
I said this was dom-0, and I'm still at dom-0.
Normally, we'd get changed to some other URL, like register.php or the like.
>> But even when I dismiss this thing by clicking OK,
notice that the URL stays completely put.
And, in fact, if I'm a little skeptical, let me open up Chrome.
Let me open up the Network tab.
And notice it's blank at the moment.
Let me go ahead and resubmit Maria.
There's no network traffic whatsoever.
So there's no HTTP.
>> So indeed, if I look at the source code for this-- let me close this window
and go to View Source.
Interesting.
It looks like there's some new tags, among them script.
So let's take a look within CS50 IDE exactly what I sent to the user.
>> So here is-- let's focus on the HTML only.
Here's the bottom half of dom-0.html.
And notice that it's got a title, a head tag, a body tag, a form tag.
But what jumps out to you as different, especially if you've never
written any JavaScript yourself.
Let me scroll a little to the right here.
I've got an input, another input for submit.
I've got an ID, which is kind of new.
But we did see this with CSS.
What else is definitely new?
Yeah?
Nice.
>> All right.
So where it says onsubmit, notice what seems to follow.
This is an attribute in HTML nomenclature.
Its value is this quoted string here.
And this looks a little weird at first glance.
It's not HTML.
It's not CSS.
This is, as you might guess, JavaScript.
So it seems that built into this web page is a function called greet.
And I'm inferring that just because it's a word, greet.
It's got an open paren, close paren, semicolon.
Looks like a C function, looks like a PHP function.
>> And indeed, it's going to be a JavaScript function.
Then I'm returning false.
We'll come back to that in just a moment.
But where is this function defined?
Well let me scroll up to the top of the file.
And even though it's a long line, it's relatively straightforward.
Let me zoom out here and focus on these four lines.
>> So in JavaScript, just like PHP, you just
say, literally, the word "function," the name of the function,
and then parentheses with any arguments-- no arguments in this case.
And there's no return type in JavaScript, just like PHP.
So it's a little looser than C. Open curly brace, close curly brace.
Built into JavaScript is a function-- not a recommended function--
but a function called alert whose sole purpose in life
is to pull up that pretty ugly prompt that we saw a moment ago.
>> Now this is kind of a mouthful.
What's going on here?
So let's start to highlight everything here.
That's the same argument to alert.
And what's going on?
This just looks like a string.
And it turns out, unlike PHP and unlike C, it doesn't matter in JavaScript
if you single quotes or double quotes.
They'll be equivalent.
And frankly, it's just popular these days
for JavaScript programmers to always use single quotes for some reason.
It's just the thing to do.
But we could use double quotes, as well.
>> So plus is a new character.
But those of you who've done this before, what does plus mean?
Yeah.
Concatenate.
So we saw this in PHP.
There's just the dot operator in PHP that
will concatenate two strings together.
C was a pain in the neck to do this.
Recall from pset six, which was an especial pain in the neck,
you would have to use something like strcat
after allocating memory on the stack or the heap.
You had to jump through hoops just to concatenate two strings.
In JavaScript, it's super simple.
Just use the plus operator between them.
>> So the complex-looking thing seems to be this
because at the end of this whole string, I just
concatenate on an exclamation point.
So if what was popping up was "hello, David," "hello, Hannah,"
"hello, Maria," and so forth, clearly that middle thing in between the two
pluses must give me access to what?
What's in there for sure?
Yeah.
So I'll pretending here the answer their name, right?
So their name popped up in the final result. So what does this mean?
Well, I proposed earlier in that picture that the so-called DOM
has this special root element way up top called document.
And now, it turns out, that's going to be a special global variable
in JavaScript, built into which is a whole bunch of useful functionality.
Among the useful functionality is the ability to get at any descendant node.
Those squares or rectangles or ellipses are just nodes in a tree, so to speak.
>> So it turns out that built into JavaScript's document object
is a function, otherwise known as a method, that's called getElementById.
The syntax for calling a function in JavaScript
that is inside of an object or a variable is just with the dot notation.
And we saw this in C what the struct syntax.
You see this in pset seven, kind of, sort of, when you see CS50::query.
The colon colon in PHP is another way of calling a function that's
inside of some object.
>> But for now in JavaScript, it's just a dot.
And so this function, nicely enough, kind of
says what it does-- get element by ID.
An element is just another name for a tag or node in the DOM.
And so get element by ID "name" means this-- here's my HTML.
And based on this HTML, what node or what HTML tag am I
going to programmatically be handed by calling document.getElementById?
>> Yeah, exactly.
I'm going to get the input element there whose ID is "name."
So specifically, you can think of this function,
getElementById, as a way of giving back a pointer to that specific node
in the tree.
We haven't drawn this tree, but it's a way
of getting access to that rectangle or that rectangle
by uniquely identifying it via its ID.
>> Now, why is this useful?
Well, it turns out that once you've gotten
that node, that rectangle from the picture, that node inside of it,
in turn, has a whole bunch of properties-- key-value pairs
or data, one of which is called value.
So literally, it's kind of a mouthful to explain the whole thing.
But at the end of the day, all this does is give you
a string that the user typed in in this hierarchical fashion.
But I don't like a couple of these things.
Or rather, there's some curiosity still.
All of that seemed to work.
Why do you think I returned false after calling greet?
This looks a little ugly, that I have two statements there
separated by semicolons.
Take a guess.
If I removed return false, what might happen, just instinctively?
Sorry, say again?
>> Open a bunch of Windows.
So potentially maybe something like that would happen.
What else?
Might submit a request where?
To the same page.
So, in fact, that's that the closer answer here,
even though, unlike in the past, I've not
specified the action attribute, which normally we have to do.
Turns out there's a default. If you don't specify action,
it's like saying quote, unquote or the name of the file itself,
which in this case would be like dom-0.html.
It's just kind of inferred, or rather implied.
>> And so if I don't do this, let's notice.
Let me save this.
And I've removed return false.
Let me go back to this example and force reload it.
And you might have seen me suggest this on CS50 Discuss a bunch of times.
If anything's ever acting funky and the browser's not behaving as you expect,
oftentimes you'll want to hold Shift and then click Reload.
That will force every file to reload and not use your browser's local cache
or copy so that now, let me go ahead and open up my Inspector, the Network tab.
I'm going to click Preserve Log because I
don't want it to delete the rows once I get whisked away elsewhere.
>> Let me go ahead here and type in Andi, click Submit.
All right.
That seems as expected.
It says "hello, Andi."
Let me click OK.
Interesting.
Notice that the page changed, albeit to the original page.
Notice the URL kind of changed.
It added a question mark, which is usually an indicator
that we tried to submit something.
And then at the bottom, even more explicitly,
here is the actual HTTP request, which got a response of 200 that
brought me back here.
>> So this is not what we want to do, right?
Because I don't want to reload the whole page.
I instead wanted to return false so as to short circuit
the browser's default behavior, which was, of course, to submit the page.
>> So let's take a look at a marginally better example.
This is dom version one.
And notice the following.
It's OK if you don't grok all of the lines of code.
But what is fundamentally different about this implementation?
I'll stipulate it behaves the same, does the same thing.
What have I obviously done differently?
Yeah?
>> AUDIENCE: [INAUDIBLE].
DAVID MALAN: Yeah.
So the function is defined differently-- in other words, absent from the form,
up there on line 7-- or rather, line 8-- no longer
do I have the onsubmit attribute.
In the previous example, I had this.
And then I literally wrote my code here.
And then I said return false.
And if it didn't rub you the wrong way yet,
it should start to insofar as, just like in HTML,
when we started to co-mingle it with CSS in style attributes,
it just started to get a little messy or feel a little wrong.
>> Similarly here, if you start taking HTML,
and then you automatically plop some JavaScript code
in the middle of a quoted string, it's not going to be very maintainable.
Right?
It's not even obvious at first place where the JavaScript code is.
So it would be really nice as a principle of better design,
let's keep our HTML completely separate from our JavaScript.
>> So to do that, what we've done here is the following--
we simply use HTML for markup only.
And so in version one of this, all I have is a form with a unique ID.
And then down here, I'm taking advantage of a special feature of JavaScript
whereby I can have what's called an anonymous function.
So it turns out that if I call document.getElementById of 'demo'
that's like giving me a pointer to this node in my tree, the form element,
so to speak.
>> Now, I just know from knowing a bit of HTML
now we're having read some online reference, that a form element supports
a whole bunch of event listeners-- in other words, the laundry list of event
listeners that we saw a moment ago.
I know from reading the documentation that onsubmit is a valid event
listener for a form element.
>> So once I know that, it's safe for me to do
the following-- get that node from the tree, the form element,
and access its so-called onsubmit property.
So the dot just means this is a property,
like a special value inside of it.
And what data type am I assigning, apparently,
to onsubmit, which is effectively a variable inside
of that node in the tree?
It's a field inside of that struct.
What's the data type?
>> A function, yeah.
So it turns out that PHP has this.
And even though we didn't tell you about it,
C also has function pointers, the ability to pass and assign functions
as variables' values themselves.
And we're not going to regress back to C.
But for now, it turns out that on the right-hand side here,
even though it looks a little funky, this means, hey browser,
give me a function.
I'm not going to even bother giving it a name because I'm literally
going to assign let's call it the address of this function
immediately to onsubmit.
In other words, browser, you don't need to know what this function's called.
You just need to know where it is in memory.
And so it suffices just to have an equal sign there
and not to bother naming this, like foo or greet or any other word.
And now this is just a stylistic thing.
I could move this curly brace onto the-- sorry-- next line
like we usually do CS50.
But in JavaScript, it's actually stylistically common
to just keep the curly brace, the first one, on that first line.
>> But hereafter, there's nothing interesting.
That open curly brace just demarcates the start of my function.
The function is now identical, except I've
included the return false inside of this function.
Because it turns out-- and you would only
know this from reading the documentation--
that if the function that you assign to the onsubmit handler returns false,
the browser just knows and agrees not to submit the form to a server.
If it returns true, it will submit it to a server for reasons we'll see
are useful in just a moment.
>> And then the semicolon after the curly brace there just
means I'm done defining the function.
You know what to call as soon as you hear a submission.
All right.
This is still arguably kind of ugly.
So what more can we do?
>> Well, it turns out then in version two, which is the last--
and we'll just glance at this.
At the risk of making it uglier, it turns out
that there's a library in the world called jQuery.
And jQuery is a super popular JavaScript library
that's so popular that most any JavaScript-- it's not
uncommon for people to confuse jQuery with JavaScript.
Why?
JavaScript itself has very verbose ways of doing things--
document.getElementById, dadadadadada.
You end up having very long lines of code.
>> So a fellow named John Resid, who actually works for a startup
up these days, came out with this library years
ago that many people have contributed to called jQuery that changes
the syntax in the following way.
And just so you've seen this, because you'll invariably
see this if doing a web-based final project,
this would be the equivalent way of implementing that same function using
this special library.
>> Now, rather than tease it apart in its entirety,
let's just look at some patterns.
This syntax appears to have how many anonymous functions
or nameless functions or AKA lambda functions?
Two, right?
And you know that, even if you're not super comfy with this,
just by the fact that it says function() twice.
>> And it turns out that what this code is doing--
and we'll refer to online references, ultimately, for some help with this.
This just means that when the document is ready,
go ahead and register the following function
as the submit handler for the HTML element whose unique idea is demo.
And then, when that happens, call these two lines of code.
And this is, tragically, a more verbose way of saying return false.
And we mentioned this just because you'll see code like this online.
And it's nothing to be daunted by.
But rather, keep in mind that what's going to be common in JavaScript
is this paradigm.
And so that's why we show it for now.
All right.
So without dwelling too much on that syntax,
are there are any questions on these examples or ideas thus far?
All right.
So let's use this for something useful.
Making a web page that just says hello, so and so isn't all that interesting,
not to underwhelm.
This one's not going to be beautiful, but it is going to do something useful.
Let me go back to my directory here and open up, say, form-0.html.
>> So suppose this is the freshman intramural sports registration page
without any CSS or any sense of design.
And I want to go ahead and register here with a password.
And I'm going to agree to the terms and conditions and click Register.
And now the website says, "You are registered! (Well, not really.)"
That seems like it worked, but let me go ahead and force reload.
>> And let me say, no, you don't need my actual email address.
Or maybe we'll just say mail in there.
Password will be, like, 12345.
And then, just because I'm an idiot, now it's 123456789.
And I'm not going to check your box.
>> Hmm.
All right.
So there's several opportunities for improvement here.
And you know, or will see in pset seven, that you can write code--
and you'll have to write code in PHP-- to defend
against these kinds of user errors because the user clearly
has not cooperated.
And he or she has not given you all the values you wanted or even in the format
that you wanted them.
So you'll see in pset seven that we could certainly have some
if conditions that say if the email address
isn't a username@something.edu, we could just
say sorry and apologize to the user much, like you might be in pset seven.
Or if they haven't checked that box, turns out in PHP, you can detect that,
too.
And certainly if the passwords don't match as in register.php
for pset seven, you can detect that.
But that's a pain in the neck in that now they request
us to go all the way to the server.
The user is informed of the error.
And at least unless you use some fancier techniques,
now they have to click the back arrow.
Wouldn't it be nice, like a lot of websites today,
if you had more immediate feedback, instantly?
>> In other words, let me go to version one, which is going to be no prettier.
But it does have this feature.
Malan, 12345, 123456789, not going to check the box, Register.
Passwords do not match.
So even though this pop-up is ugly-- we can replace this eventually
with something like Bootstrap, which you'll see in pset seven
is a very popular library-- I did detect that the passwords do not match.
All right.
Well, let me fix that as the user.
Let me go ahead and say 12345, 12345.
Still not checking the agreement.
You must agree to the terms and conditions.
So why?
>> If we've already posited that there's a way,
and we've required you in pset seven to detect error
conditions like this server-side, why should I
bother also doing this in JavaScript?
What's an argument in favor of adding what
you're about to see as some-- there's additional complexity.
>> Maybe there is no upside.
What could it be?
AUDIENCE: [INAUDIBLE].
DAVID MALAN: Oh, interesting.
Potential exploits.
So sure, if you're not handling erroneous user input that great,
maybe it's all the better if it doesn't even reach your server.
I would push back there and say, you should probably
fix both of those problems.
But that's fair.
What else?
>> AUDIENCE: [INAUDIBLE].
>> DAVID MALAN: Yeah.
This code, as we said before, is interpreted on the client-side.
It doesn't bother the server, which means it doesn't
impact the server's load or capacity.
And now, for little old me, this has no meaningful effect
because I have one user right now.
>> But if you're any website of decent size,
especially the biggest, like Facebook, the more you can keep people off
of your server the better because a server, of course,
only has a finite amount of RAM, a finite number of gigahertz,
a finite number of things it can do per unit of time.
So if there are more people in the world hitting your server,
accidentally logging incorrectly, just as well if you
can keep that load off your server.
Plus, especially on a mobile device-- if you've ever
log into my.harvard or Yale's netid or the like,
there's this the latency with a lot of websites like that whereby it takes,
like, a damn second or two sometimes.
And then, my God, if you mistype, then you have to hit back and redo it.
So there's latency, especially on slower network connections.
But JavaScript, because it runs on the client
and doesn't need to go back and forth across a potentially slow internet
connection, you can get nearly instantaneous feedback.
>> So let's look at this.
Let me open up form-0 and look at the HTML here.
And let's just see what's going on.
This is a form whose action is register.php.
I'm just using get so that I could see the URL.
But for passwords, we'd surely want to change this to post in reality.
Here's an input field of type text.
Here's another input field of type password.
Here is, if you've never seen, an input of type checkbox.
>> But there's no JavaScript here whatsoever.
This is just HTML that goes to register.php.
But in version one, where I started to get those pop-ups,
let's see what actually happens here.
In version one, what I'm going to see-- I
thought I could stall enough with enough words, but I ran out.
>> In version one-- there we go.
In version one, notice the following-- and is not the best implementation,
but it's my first.
Notice that below the form, I have a script tag.
And a script tag means, hey, browser, here
comes some code in, typically, JavaScript.
And now, notice what I'm doing.
On line-- I can barely read it-- line 32, it says,
var form-- so give me a variable called form.
And then get document.getElementId of "registration."
What is this?
Well, let me rewind up here.
And notice, ah, I gave the form element an arbitrary but descriptive idea
of registration.
So this gives me a variable that allows me to grab that node,
that rectangle in the tree called form.
form.onsubmit means, hey browser, register an event listener
on this form.
In other words, when this form is submitted, execute the following code.
It doesn't need a name because why do you need to know the name?
You just need to know what to execute, ergo
it's an anonymous or lambda function.
And that function is all of these lines here.
And now, to be honest, even though you might not have ever written JavaScript
before, it's just C and PHP logic.
So if form.email.value==" "-- so if the email field is blank,
yell at the user with "You must provide your email address."
Else if form.password.value is blank yell at the user,
"You must provide your password."
>> More interestingly logically, if form.password.value does not
equal form.confirmation.value-- where did confirmation come from?
Let me rewind.
Well, I called this input field here password.
And I called this one here confirmation.
I could have called it password two or anything else.
I'm just logically checking that these two are the same.
Else-- it turns out this is Mr. Boole again-- a Boolean value, the check box.
So if I say, exclamation point-- if not form.agreement.checked,
yell at the user as well.
>> So this syntax you'll see is very common in JavaScript,
where you have this dotted notation.
You start with an object here.
You dive in deeper to a to a property like password.
And then you get at its actual value.
And again, here is the input.
Here is the name password.
And its value is whatever the human has actually typed in.
>> So in all of these cases, I returned false.
But if not, I return true.
And so now we see a compelling use of when
you would return false to stop what the user's doing
and make him or her choose again or type again.
Otherwise, we return true.
>> And let me introduce one other variant of this just
to seed some understanding thereof.
Well, in version 2 of this, form-2-- I'll do it with a wave of a hand.
This is, for those curious, the jQuery version,
those of you who might want to dabble in that particular library.
But let's start-- and any questions?
Let me pause for moment because that was fast and a lot.
>> But the nice thing here is that all of the code is pretty much the same.
The new stuff is what is the dom?
What are these rectangles?
What are these nodes?
What's an anonymous function?
What's an event handler?
But thankfully, most of that is just full circle from, say, week zero.
All right.
So something slightly more interesting?
Well, first of all, let me go ahead and open up Google Maps.
And you'll notice that for a moment, on the split second,
notice what happens when I click fast enough.
And this connection at Harvard is so fast that you don't really notice it.
But what do you kind of sort of see if I click and drag really fast?
Those of you watching online, if you slow this to 0.5x speed,
you can see this better.
>> What was happening just before I clicked and dragged?
Let me try here-- let me do something else, like 90210.
Let's go far away.
That was really fast, too.
How about Disney World?
There we go.
OK.
What did you see for a split second?
Just, like, squares, right?
Placeholders for tiles?
>> Well, what's going on here?
Google Maps is a nice example of this technology that's called AJAX.
And this is where we'll start to use the JavaScript in a particularly
alluring way.
Back in the day, there was this website called MapQuest.
And I should have taken a screenshot of this from the 1990s,
where if you wanted to look up here on the map,
you would literally click an arrow up at the top that showed you
a different square of the map.
If you wanted to move left, you clicked an arrow that showed you
a different square of the map.
And some websites still do this today.
But even MapQuest has gotten better, like Google Maps.
>> Instead, what's better these days is websites that use AJAX.
AJAX-- otherwise known as Asynchronous JavaScript and XML,
which is just a fancy way of saying a technology or technique that
allows a browser using JavaScript to make additional HTTP requests
after the page has been loaded.
So what does this mean?
Well, it would be kind of annoying in Gmail
if every time you wanted to check your mail,
you had literally hit Control-R or Command-R or click the Reload button
and the whole darn page would reload.
Right?
It would flash white probably for second.
You would see the stupid progress bar.
And just to see if you have new mail, the whole web page and the URL
you're at would have to reload.
>> But that's not what happens in Gmail.
Right?
When you get a new email in Gmail, what happens on the screen?
It just shows up, right?
It just magically appears as a new row in the table.
That actually involves a decent amount of complexity.
In fact, if you think about this tree, which even though is a simple one here,
Gmail-- and I'd have to look at the code to be sure--
probably has an HTML table or maybe an unordered list that it renders
each of your inboxes emails as.
>> And so if you imagine this there is a tree in memory when you're
using Gmail that looks kind of sort of like this, when Google realizes, ooh,
you have a new email, it doesn't want to rebuild the whole tree.
Rather, it wants to find the node in the tree that represents your inbox
and just insert a new node.
>> So very similar to pset five, where you had to insert nodes into a hash table,
similarly does Google, via JavaScript code that it has written,
traverse this tree, figure out where is that inbox part of the window,
and then insert a new row.
And a new row just means one or more new nodes in a tree.
>> And so AJAX is this technique that allows for exactly that.
Once you've visited a URL, however crazy long it is,
and once the page has been loaded, you can still
grab more data from the internet-- whether it's
an email or a tile of a map-- grab it behind the scenes
and then insert it into the page so that the human doesn't really
have to wait for it.
>> Facebook Messenger works the same way.
Any number of other websites-- oh, actually, even this.
I mean, this is, frankly, kind of an annoying feature these days.
If I start searching for cats-- this is kind of a horrible user experience.
It just starts searching for me.
Well what is it doing?
The URL hasn't really changed since I started typing.
But what's going across the wire-- OK, hmm interesting.
What's going across the wire here just gets weirder.
>> OK.
So let me go ahead and inspect element and go to the Network tab
and try to make this technical and less about cats.
As I type, literally, cats and-- what's happening
per-- I'm not going to click that.
All right.
So down here, what's happening every time I type a character, apparently?
Like, low level?
What's happening with each of those characters I'm typing at my keyboard?
Yeah?
AUDIENCE: [INAUDIBLE].
>> DAVID MALAN: Exactly.
Each of those characters is going to Google, one at a time.
They are building up a string on their server that represents
everything I've typed in thus far.
And every time I type another character, they
use their secret sauce of a search algorithm and figure out,
does he mean this cat page or this cat page or the like?
So in some sense, it provides me with a better experience in that I don't even
need to complete my thought.
And indeed, it's a useful thing, autocomplete in general.
If their algorithms are good enough and if my searches are obvious enough,
I don't have to type the whole word.
They're going to tell me what it is I'm actually searching for.
So what Google calls instant search is just using AJAX,
using code that allows them to request additional content via a web browser
behind the scenes using this new language, JavaScript.
So we have a couple minutes left.
And let me call up my buddy Colton up onto the stage,
since it seemed particularly fun last time
to introduce a technology that some of you
have expressed an interest in for final projects.
We thought it'd be fun to bring up a volunteer, though, today
to show you an addition to this that allows you-- yeah,
I saw this hand first.
Come on up.
Very well done.
Good job.
I'm going to project this on the screen in just a moment.
What's your name for everyone?
>> EFA: I'm Efa.
>> DAVID MALAN: Etha?
>> EFA: Efa.
>> DAVID MALAN: Efa?
>> EFA: Yeah.
>> DAVID MALAN: Nice to see you.
All right.
Let me get this ready.
Come on over to the middle with Colton here.
What Colton has in his hands today is a remote control.
So rather than just stand there in a three-dimensional world looking around
as Colton did, now Efa can actually walk around by going up,
down, left, and right like a Nintendo or Xbox controller.
EFA: I'm going to fall off the stage.
DAVID MALAN: I will stand roughly over here.
But that is a risk.
OK.
So go ahead and put those on.
Let me go ahead and switch to the screen here.
Let me dim the lights.
And Colton, let me come stand next to you.
>> Do you want to explain here with the mic what we're doing?
Here you go.
>> COLTON: Sure.
So right now we're loading up the Oculus,
I guess operating-- not operating system, but the main program, where
you can access all the games and apps that are in your library.
So right now, it should say tap the touchpad to begin.
Touchpad's going to be on the right side of the headset.
So go ahead and tap--
EFA: Oh, man.
DAVID MALAN: Yeah, there you go.
The quality Efa is seeing is much higher quality.
This is just the Wi-Fi here.
COLTON: So what you're going to want to do
is look towards the top right of the screen.
Yep, that game on the very top right.
And then when you're selecting it, tap the touchpad again.
I think its Dreadhalls.
And then here is a-- here, let me hold your glasses for you.
>> So I just gave him a controller.
So now he can control the game.
He can move around and stuff like that.
So go ahead and look up to the top.
You should see New Game.
So go ahead and you can do that.
Now, you should be able to control yourself with the controller,
as well, as soon as the game loads up here.
This might be a little bit scary.
>> EFA: Now you tell me.
OK.
>> COLTON: All right.
So confirm that you can move around.
OK.
You can move around.
Perfect.
So if you look down, you have a map.
Map shows you where you are.
You can look around the room.
You can completely turn around.
Yeah, exactly.
Turn around.
>> So look to your left.
I think there's something you can pick up on a barrel in the room.
>> EFA: How do I get the map out of the way?
COLTON: Look up.
Just look up.
All right.
There you go.
Now go ahead and just turn around.
So look farther to your left.
Keep moving left.
Keep looking left.
Keep going.
Yeah.
>> EFA: Oh, that way.
>> COLTON: Yeah.
Walk towards it with the controller.
There you go.
Now it should say pick it up.
There you go.
Pick it up.
All right.
Now, let's get out of this room.
Go ahead and walk to that door.
So you're going to hold-- it says hold the button to force it open.
So go ahead and hold the button.
Yep, forcing it open.
All right.
Good job.
Now we're walking out of the room.
So I'm going to leave the rest up to you and see what you find out.
EFA: I'm not going in the dark room.
Oh, wait.
Now I have to go down the dark hall?
OK, I'm going back [INAUDIBLE].
COLTON: All right.
Some more items to pick up.
Looks like some coins.
That's a lock pick.
So if you find a locked door, you can use that.
Are you scared?
>> EFA: Not yet.
COLTON: OK.
>> Pretend-- yeah.
Just pretend you're actually standing there.
And if you turn around-- you've got to get used to it.
But it makes sense.
DAVID MALAN: And while Efa continues to play, since we could do this all day,
we can all tip-toe out here.
But we do have two other pairs, if you'd like to come up and play.
Otherwise, we will see you next on Wednesday.
Thank you to our volunteer today.
[APPLAUSE]
>> [MUSIC - "SEINFELD THEME"]
SPEAKER 1: Well, I'm putting a new PL mount on.
I just changed the OLPF--
>> SPEAKER 2: So what exactly are you doing?
>> SPEAKER 1: Well, each one of these-- here, I'll show you this one in here.
You can see it right here.
>> SPEAKER 3: I think I'm good with these.
You want some more?
>> SPEAKER 4: No, I'm good. [INAUDIBLE].
>> SPEAKER 3: No, [INAUDIBLE].
Have some.
SPEAKER 1: Different color.
SPEAKER 2: OK.
SPEAKER 1: So ultimately what it does is it adjusts the color of--