JavaScript - CS50 Shorts

CS50 · Beginner ·💻 AI-Assisted Coding ·8y ago

Key Takeaways

Introduces JavaScript in CS50 Shorts

Full Transcript

So near CS50's end we introduce you to a several different programming languages and we aren't able to cover them in nearly in as depth as we were able to cover C earlier in the course. The goal here is not to give you a complete rundown of what these languages do but to give you enough of the basics and show you enough of the parallels to things that you already know so that you can go forth and really you know flesh out your knowledge of these different languages. And another one we're going to cover right now is JavaScript. Now similar to other languages you've discussed it is a modern programming language that has a is derived from C's syntax. So if you're familiar with C you're going to be able to pick up JavaScript pretty quickly. It's been around just about as long as Python. It was invented a few years afterwards in the mid 1990s. Now it's really important about JavaScript as well as HTML and CSS as we've discussed in other videos is that those three languages pretty make pretty much make up the core user experience of what it means to be online. So understanding how to use and work with JavaScript, HTML, and CSS will allow you to really create websites that users will enjoy visiting because you'll be able to create a great user experience for them with these three languages. To write JavaScript it's really easy. Open up a file with a .js file extension and start writing a JavaScript right away. If you're familiar with a language like PHP you know that you have to sort of bind your code up in these delimiters, bracket, question mark, PHP, and all that stuff. We don't have to do that in JavaScript. We literally just start writing our code in a JavaScript file which is pretty nice. Our website will also know that what our file is is JavaScript because we're going to tell it in an HTML tag. We're going to say I have a script that is of type JavaScript and it is a file with a .js file extension. Pretty straightforward. Now unlike Python which runs on the server side that is on the side that is hosting the website JavaScript applications run client side on your own machine when you are visiting a website. To include JavaScript in your HTML it's pretty easy. Just like when we include CSS with style tags we can include JavaScript in between script tags. We can have an open script tag and literally start writing JavaScript right in our HTML which is kind of cool. But also like CSS where we had link tags we can write our JavaScript in a different file and connect it using the source attribute of a script tag. In CS50 and really probably more generally this is definitely the preferred way to go particularly if you have a JavaScript file that might be used or the contents of which might be used on different pages of your website. You don't want to have to write the JavaScript between the script tags on every single page. You want to be able to just refer to an outside file and link that in every single time. So let's quickly run down some of the different things you might fundamentals that you might use in JavaScript. So variables they're really similar to Python variables and really similar to C variables. No type specifier is required and if you want a local variable you preface it with the var keyword. So in Python we would say something like this x = 44. We don't want to do that in JavaScript cuz that would actually create a global variable if we were to put a semicolon at the end. We would want this var x = 44. That creates a local variable called x in JavaScript and stores the value 44 in it. Conditionals all of the old favorites from C are available for you to use. If, else if, else, switch, question mark, colon all of those are fair game. We're not going to get into detail on those at all because we cover them in our videos on C but they're all here to use in JavaScript and behave pretty much exactly the same. Loops meanwhile all of the ones we're familiar with from C are also still available. While loops, do while loops, and for loops although we do have a couple of other variations that we'll talk about in just a little bit. Now functions in JavaScript are all introduced with the function keyword. So we say function, provide a function name, any parameters, and then we define our function between curly braces just as we would in C except in C of course we're not using the function keyword. But there's also a catch with JavaScript which is that functions can be anonymous meaning you don't have to give them a name. Now you might be asking yourself wait how can I call a function if it doesn't have a name? We'll talk about that in just a little bit and we'll talk about what I mean in particular here when I'm describing binding things to HTML elements. We'll talk about that in the video on the document object model. But we'll talk about anonymous functions in just another minute. I'll give you an example and you can see how they might be useful in certain contexts. And those contexts actually do kind of materialize a lot in JavaScript programming. JavaScript like C and like Python or analogous to Python's lists has arrays and you can declare an array. It's pretty straightforward. So for example var nums creates a local array and then I have square brackets and I just have a comma separated list of all the values that I want to put in the array. I can also mix types. I I don't have to have all integers or all floats or all strings like I do in C. I can have different types mixed together there. JavaScript has the ability to behave a few different ways and that's why it can be a little bit tricky as a very first language to learn because it sets up a bunch of rules for itself and then breaks them. It is very very flexible but it perhaps almost a little too flexible as a first language. But it can behave as an object oriented programming language. An object oriented might be a term that you've heard before but if not we'll try and give you a quick little crash course here. An object is really similar in spirit to a structure that we are familiar with hopefully from C. Now in C structures can have a number of different fields or members. Another term for those that we see commonly in object oriented programming are properties. But those properties or fields or members just like in C can never stand on their own. So for example if we define the structure for a car like this struct car and inside of that there are two different fields or members int year and char model 10. So a 10 character string that we can use to store the car's model. We can do things like this. We can say struct car Herbie which declares a variable of type struct car named Herbie. And then we can say Herbie.year = 1963, Herbie.model = Beetle. That's totally fine. That's valid C. But we can never say this in C. We can never say year = 1963, model = Beetle. Now we can't say that because year and model are so fundamental to what it means to be a struct car. They are part of a struct car and so if we're ever using year and model sort of in the we can't use them in the abstract. We always have to associate those things with a particular struct car. So that is not okay. Objects in addition to having fields or members or properties also have something called methods which is sort of like if a C structure had a function that could only ever apply to that structure. So it's it's as if we have a function where structures are the only things that can be passed in. Now that we have in C. But we can't like we can't define a function inside of a curly the curly braces of a struct. That is more that is object oriented programming. That is different from here. So but just like properties methods don't stand on their own either. It's not like a function that just exists in the abstract. It is a function that only exists in the context of in this case an object. So where we might do this in C function parentheses object where object is a parameter to the function being called that is not object oriented styling. Object oriented means the object is sort of at the core of everything. And instead we're going to call this function that is a part of the object. Okay? So this is what object oriented programming looks like in a very very basic form is there are functions that are affiliated or associated with objects and we call those functions as follows by execute by specifying the object and saying we want to do we want some function to execute on that object like this. The fields and methods of an object are really similar in spirit to the idea of a dictionary which you may be familiar with or recall from Python. So we could example have something like this var Herbie equals curly braces now now not square brackets. It's curly braces and then a comma separated list of key value pairs where year 1963 is sort of like saying Herbie.year = 1963 in C. And Herbie.model or excuse me yeah Herbie.model = Beetle. That's this is akin to how we would do the same thing in JavaScript by creating an object and giving it a couple of properties right away. All right. Now let's go back to loops cuz I mentioned earlier there are a couple of different new loops that we can use in JavaScript. So now that we have this object how would we maybe iterate across all of the key value pairs of that object? Or in fact how would we iterate across all of the elements of an array if we wanted to do that besides using a for loop, a while loop, or a do while loop? So in Python we saw something like this for key in list and then we would have some code where we would use key every point from there on down as sort of a stand in for the ith element of the list. We can't do that in JavaScript but we can do something pretty similar for var key in object and then open curly brace. Between those curly braces we can use object square bracket key to refer to the keyth element of the object or the keyth key in a key value pair set of the object. We also have a slightly different variation for var key of object which instead of having to use object square bracket key we can now refer to iterating across all of the values as opposed to this which iterates across all of the keys this would iterate across all of the values. We can cover both sides of a key value pair using for var key in or for var key of. Here's an example of an array where we're going to use these two different types of loop. So we have here a week array that has seven elements in it Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday and I want to use a four var day in week array. So I want to use a four in loop and I want to console.log. Console.log is sort of the JavaScript equivalent of printf. You can access it using developer tools in most modern browsers. Um what's going to happen when I print this out? It's going to print out a list of all of the keys. Well, in this array there's really no keys. There's a bunch of indices. So this would print out 0 1 2 3 4 5 6 because there are seven elements of my array and I'm logging which element I'm talking about. If I wanted to print out the days instead, I would do I would use a four of loop and I would get the following printed out to the console. Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday. What if I want to concatenate information? So remember we can um tie different strings together. We can do that in Python. We can do it as well uh here in JavaScript. Um and we do that by using plus. So if I want to console.log a bunch of different strings concatenated together, I just use plus to do it. But here's a little bit of a catch, right? If I'm using plus, now it means two different things. I want to concatenate strings together, but maybe here I want to add. I really encourage you to take a look at what happens if you cons if you have the you write the week array into some JavaScript and then have a loop that iterates across and console.logs this. Um you might find that you get something that you don't expect. And so JavaScript is making its best guess and it's assuming that day and one are both strings when really what I want to do is add them together literally cuz they're numbers. Um but fortunately JavaScript gives us a way around that by using a function called parseInt. Now this is going to give us what we expect to see. This on the other hand is going to give us something we don't expect to see. But it's just again a case of we're using the same operator to mean two different things and the language sometimes has to make a best guess. So it's not always a great thing that languages nowadays uh don't often require us to specify a data type. If we were able to specify a data type here, we would be able to disambiguate this. But here with JavaScript, it thinks it's being very helpful for us by not specifying a type and when it's going to make our best guess as to what we want to do, but sometimes it guesses wrong. But it gives us ways to work around it if it does indeed guess wrong. So arrays um are also are actually a special case of an object. And actually in JavaScript, everything is a special case of an object. X, any variable, var x equals 44, that's an object that just happens to have one property. Arrays are an object that happens to have uh a number of properties and also some certain methods that can be applied to them. So we can call uh the size method or pop or push or shift and I'll leave to you to figure out or to do some research into what those different things are. But suffice it to say that they are functions that are basically so baked into what it means to be an array that we can just call them without having to write them in the first place. That's pretty cool. Here's another cool thing that you can do with arrays. There's a there's another uh method for them called map, which basically allows us to apply a function to every single element of an array. And in particular, this is a great example for using an anonymous function. So let's take a look at how we might use an anonymous function and why it might be useful to do so. So here's an array called nums. It has five elements in it, 1 2 3 4 and 5. Now what I want to do is I want to map some function on to them. So what I'm saying here is nums equals so I'm going to do something to nums and I'm going to reassign that back to nums. Nums equals nums.map and remember map takes in a function. It's a function that I want to apply to all of the members or all of the elements of that array. One thing I could do is just write this function somewhere else and give it a name and say so say I called it what what's going to happen here is every value is going to be doubled. Let's say that I wrote a function called double numbers. I could say nums equals nums.map {double numbers} double numbers and it would just double every number. That would be fine. But here, notice I'm using that function keyword and I'm giving a list of parameters in this case num, but I'm not giving that function a name. Why am I not giving that function a name? Well, I'm just doing this mapping here. I'm never going to need to double these numbers again. Why am I going to clutter up the name space and give up, you know, some give it some name when I'm never going to use it again outside of this context. It's kind of convenient that we can actually use a function in this case then without having give having to give it a name and still have it do what we want to do. So all I'm doing here inside of those parentheses of map is the open parentheses on the first line there and that close parentheses is actually on the third line and in between the parentheses where I'm specifying the parameter to map, I'm literally defining an entire function in there. And then if I execute this line of code, what's going to happen to nums? Well, you can probably guess. It's going to just double every element of nums. All right, one more thing I want to touch on really quick about JavaScript and that is the notion of events. So an event is sort of something that it goes hand in hand with HTML and JavaScript and it is a response to a user doing something on a web page. So for example, perhaps they click a button. Perhaps the page has finished loading after the user hits refresh for example. Maybe they've hover over a portion of the page or something like that. All of those things are events. And JavaScript has support for what it's called an event handler, which is some JavaScript code that will execute once that event has taken place. So it allows our site page to be very interactive. If we um type in a box for example, we could have an event uh handler that pops up a message that says, "Please enter your password." So it's just a completely it's an empty field that says nothing at all. You start to type in it and then this box pops up because you've started typing, which is an event on the page, and it tells you to do something. That is a JavaScript event handler taking effect. Many elements of HTML have support for events as an attribute. So here's an example of some really basic HTML. I have my head and my body and inside of the body, there are two buttons and they have this attribute called onclick. Onclick is a definition basically for an event handler so that I want something to happen when I click the buttons. Right now it's nothing, but I can put something in there so that when I click on either of those buttons, that function that's in between the quotation marks there would get called. Um we can write a really generic event handler in JavaScript for example that creates um an event object and will tell us which of those two buttons were clicked and it might look something like this. Button onclick equals alert name event. If we do this, we have basically set up our HTML so that when either button one is clicked or button two is clicked, the alert name function will be called and an event will be passed in. The event is automatically generated by the page and it basically contains all of the information about what just happened. And from that information, we can extract more information. So for example, here is what the alert name function might look like and notice that here I'm also accepting an event parameter. What am I doing then? I'm getting a new JavaScript local variable called trigger and I'm asking for that event's source element. And what that is basically telling me is what is the element on the page that was interacted with that triggered this event? Or rather to put it another way, what element effectively was passed in to this function? Cuz again, this is automatically generated. The page knows which button we touched and so basically what's happening here is that button, whichever one of the two it was, is getting passed into this function. Then, and you'll see a little bit more of this when we talk about the document object model, I can access that trigger's inner HTML to figure out which uh which button was clicked. Now what is inner HTML? Let me jump back a couple slides for a second here. The inner HTML is what is between the button tags. In this case, button one is inner HTML and button two is also inner HTML. So what happens when I click on those buttons is it will alert to me, "You clicked on button one." if I happen to click on button one, or "You clicked on button two." if you happen to click on button two. Now again, we are just scratching the surface of JavaScript, but I wanted to give you a sense of some of the different things that you can do so that you can then go forward look at the documentation and see the very wide range of things that you can do as well by just applying some of the basic tenants that we've learned about in CS50 and really expanding um your knowledge exponentially. I'm Doug Lloyd. This is CS50.

Original Description

*** This is CS50, Harvard University's introduction to the intellectual enterprises of computer science and the art of programming. *** HOW TO SUBSCRIBE http://www.youtube.com/subscription_center?add_user=cs50tv HOW TO TAKE CS50 edX: https://cs50.edx.org/ Harvard Extension School: https://cs50.harvard.edu/extension Harvard Summer School: https://cs50.harvard.edu/summer OpenCourseWare: https://cs50.harvard.edu/x HOW TO JOIN CS50 COMMUNITIES Discord: https://discord.gg/T8QZqRx Ed: https://cs50.harvard.edu/x/ed Facebook Group: https://www.facebook.com/groups/cs50/ Faceboook Page: https://www.facebook.com/cs50/ GitHub: https://github.com/cs50 Gitter: https://gitter.im/cs50/x Instagram: https://instagram.com/cs50 LinkedIn Group: https://www.linkedin.com/groups/7437240/ LinkedIn Page: https://www.linkedin.com/school/cs50/ Reddit: https://www.reddit.com/r/cs50/ Quora: https://www.quora.com/topic/CS50 Slack: https://cs50.edx.org/slack Snapchat: https://www.snapchat.com/add/cs50 Twitter: https://twitter.com/cs50 YouTube: http://www.youtube.com/cs50 HOW TO FOLLOW DAVID J. MALAN Facebook: https://www.facebook.com/dmalan GitHub: https://github.com/dmalan Instagram: https://www.instagram.com/davidjmalan/ LinkedIn: https://www.linkedin.com/in/malan/ Quora: https://www.quora.com/profile/David-J-Malan Twitter: https://twitter.com/davidjmalan *** CS50 SHOP https://cs50.harvardshop.com/ *** LICENSE CC BY-NC-SA 4.0 Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License https://creativecommons.org/licenses/by-nc-sa/4.0/ David J. Malan https://cs.harvard.edu/malan malan@harvard.edu
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from CS50 · CS50 · 0 of 60

← Previous Next →
1 Hello, World: Hadi Partovi
Hello, World: Hadi Partovi
CS50
2 Content Distribution and Archival in a Digital Age
Content Distribution and Archival in a Digital Age
CS50
3 CS50 2014 - Week 1
CS50 2014 - Week 1
CS50
4 CS50 2014 - Week 3
CS50 2014 - Week 3
CS50
5 CS50 2014 - Week 0, continued
CS50 2014 - Week 0, continued
CS50
6 CS50 2014 - Week 4
CS50 2014 - Week 4
CS50
7 Week 3, continued
Week 3, continued
CS50
8 Quiz 0 Review
Quiz 0 Review
CS50
9 CS50 2014 - Week 3, continued
CS50 2014 - Week 3, continued
CS50
10 CS50 2014 - Week 7
CS50 2014 - Week 7
CS50
11 CS50 2014 - Week 7, continued
CS50 2014 - Week 7, continued
CS50
12 Breaking Through The (Google) Glass Ceiling by Christopher Bartholomew
Breaking Through The (Google) Glass Ceiling by Christopher Bartholomew
CS50
13 Introduction to Amazon Web Services by Leo Zhadanovsky
Introduction to Amazon Web Services by Leo Zhadanovsky
CS50
14 CS50 2014 - Week 9
CS50 2014 - Week 9
CS50
15 How to Build Innovative Technologies by Abby Fichtner
How to Build Innovative Technologies by Abby Fichtner
CS50
16 Light Your World (with Hue Bulbs) by Dan Bradley
Light Your World (with Hue Bulbs) by Dan Bradley
CS50
17 Building Dynamic Web Apps with Laravel by Eric Ouyang
Building Dynamic Web Apps with Laravel by Eric Ouyang
CS50
18 CS50 2014 - CS50 Lecture by Steve Ballmer
CS50 2014 - CS50 Lecture by Steve Ballmer
CS50
19 CS50 2014 - Week 10
CS50 2014 - Week 10
CS50
20 This is CS50 with Steve Ballmer?
This is CS50 with Steve Ballmer?
CS50
21 Meteor: a better way to build apps by Roger Zurawicki
Meteor: a better way to build apps by Roger Zurawicki
CS50
22 Data Analysis in R by Dustin Tran
Data Analysis in R by Dustin Tran
CS50
23 Data Visualization and D3 by David Chouinard
Data Visualization and D3 by David Chouinard
CS50
24 CS50 2014 - Week 6
CS50 2014 - Week 6
CS50
25 Build Tomorrow's Library by Jeffrey Licht
Build Tomorrow's Library by Jeffrey Licht
CS50
26 CS50 2014 - Week 9, continued
CS50 2014 - Week 9, continued
CS50
27 Essential Scale-Out Computing by James Cuff
Essential Scale-Out Computing by James Cuff
CS50
28 iOS App Development with Swift by Dan Armendariz
iOS App Development with Swift by Dan Armendariz
CS50
29 Sam Clark Leads Yale Students on Tour to CS50 at Harvard
Sam Clark Leads Yale Students on Tour to CS50 at Harvard
CS50
30 3D Modeling and Manufacture by Ansel Duff
3D Modeling and Manufacture by Ansel Duff
CS50
31 CS50 2014 - Week 5, continued
CS50 2014 - Week 5, continued
CS50
32 hello, world
hello, world
CS50
33 CS50 2014 - Deep Thoughts - Hash Table
CS50 2014 - Deep Thoughts - Hash Table
CS50
34 CS50 2014 - Deep Thoughts - Binary Tree
CS50 2014 - Deep Thoughts - Binary Tree
CS50
35 CS50 2014 - Deep Thoughts - Scratch
CS50 2014 - Deep Thoughts - Scratch
CS50
36 CS50 2014 - Deep Thoughts - MySQL
CS50 2014 - Deep Thoughts - MySQL
CS50
37 LaunchCode Visits CS50
LaunchCode Visits CS50
CS50
38 CS50 Live, Episode 100
CS50 Live, Episode 100
CS50
39 CS50 Field Trip to Google
CS50 Field Trip to Google
CS50
40 This is CS50 AP
This is CS50 AP
CS50
41 Week 4: Monday - CS50 2011 - Harvard University
Week 4: Monday - CS50 2011 - Harvard University
CS50
42 Week 2: Wednesday - CS50 2011 - Harvard University
Week 2: Wednesday - CS50 2011 - Harvard University
CS50
43 Week 1: Wednesday - CS50 2011 - Harvard University
Week 1: Wednesday - CS50 2011 - Harvard University
CS50
44 Week 11: Monday - CS50 2011 - Harvard University
Week 11: Monday - CS50 2011 - Harvard University
CS50
45 Week 3: Wednesday - CS50 2011 - Harvard University
Week 3: Wednesday - CS50 2011 - Harvard University
CS50
46 Week 12: Monday - CS50 2011 - Harvard University
Week 12: Monday - CS50 2011 - Harvard University
CS50
47 Week 1: Friday - CS50 2011 - Harvard University
Week 1: Friday - CS50 2011 - Harvard University
CS50
48 Week 3: Monday - CS50 2011 - Harvard University
Week 3: Monday - CS50 2011 - Harvard University
CS50
49 Week 10: Wednesday - CS50 2011 - Harvard University
Week 10: Wednesday - CS50 2011 - Harvard University
CS50
50 Week 2: Monday - CS50 2011 - Harvard University
Week 2: Monday - CS50 2011 - Harvard University
CS50
51 Week 9: Monday - CS50 2011 - Harvard University
Week 9: Monday - CS50 2011 - Harvard University
CS50
52 Week 7: Monday - CS50 2011 - Harvard University
Week 7: Monday - CS50 2011 - Harvard University
CS50
53 Week 5: Monday - CS50 2011 - Harvard University
Week 5: Monday - CS50 2011 - Harvard University
CS50
54 Week 5: Wednesday - CS50 2011 - Harvard University
Week 5: Wednesday - CS50 2011 - Harvard University
CS50
55 Week 7: Wednesday - CS50 2011 - Harvard University
Week 7: Wednesday - CS50 2011 - Harvard University
CS50
56 Week 8: Monday - CS50 2011 - Harvard University
Week 8: Monday - CS50 2011 - Harvard University
CS50
57 Week 9: Wednesday - CS50 2011 - Harvard University
Week 9: Wednesday - CS50 2011 - Harvard University
CS50
58 Week 8: Wednesday - CS50 2011 - Harvard University
Week 8: Wednesday - CS50 2011 - Harvard University
CS50
59 Week 10: Monday - CS50 2011 - Harvard University
Week 10: Monday - CS50 2011 - Harvard University
CS50
60 Week 2: Wednesday - CS50 2010 - Harvard University
Week 2: Wednesday - CS50 2010 - Harvard University
CS50

Related Reads

📰
The Collapse of ‘Who Understands, Who Maintains’ — A Software Landscape in the AI Age
The increasing complexity of code due to AI is outpacing human understanding, leading to a collapse of the 'who understands, who maintains' principle in software development
Medium · Programming
📰
Building an OpenAI + Azure SQL App from Scratch
Learn to build an app combining OpenAI and Azure SQL from scratch, a unique approach differing from typical Postgres-based tutorials
Medium · Python
📰
Breaking the Abstraction Tax: Mastering Custom C++ Operations for High-Performance Edge AI on Android
Learn to optimize Edge AI on Android using custom C++ operations to break the abstraction tax and achieve high-performance
Dev.to · Programming Central
📰
Five Habits I'm Unlearning After Claude Code 101
Learn how to effectively use Claude Code 101 by unlearning common habits and understanding its true potential beyond a fancy autocomplete
Medium · Data Science
Up next
How to Start a SaaS Business in 2026
Learn With Shopify
Watch →