What do you want to learn?
Skip to main content
by Mark Zamoyta
Start CourseBookmarkAdd to Channel
Table of contents
Introduction and Setup
Course Objectives and Overview
Tooling for This Course
Setting up a Development Environment
The value of a variable can change during the execution of a program; however, sometimes we want to use a symbol that won't change and that type of symbol is called a constant. Here's how we declare a constant. We use the const keyword for constant and it looks a lot like a variable declaration. The constant is called carId and we're initializing it to 42 and one of the rules about constants is that it must be initialized. Here we're trying to create a constant called bodyStyle, but that will generate an error. Unlike a variable a constant needs to be initialized and in this example we have a constant carId set to 42, but then later on in the source code the developer tries to assign the value 100 to carId and that will generate an error. A constant can't be changed. It can only be initialized. So here's the development environment we set up in the first module. I have Visual Studio Code running on the left side and we're working in the index.js file and on the right side we have our browser. Let's pull up a terminal quickly, Control+backtick on a Mac, and let's start our development server, npm run dev. And in our browser I'll open up the console and this is where we'll log our output. So let's create a constant. Use the const keyword. We'll name it carId and let's see what happens if we don't initialize it. I'll save the file and we get an error. We get an unexpected token after carId because we need to initialize a constant. We'll initialize carId to 100 and save it and now everything's fine. If later on in our code we try to assign a value to carId, you can see we get an error. CarId is read-only. So why would you want to use a constant instead of a variable? The key reason is to avoid programmer error in the future. If a value shouldn't change it should be declared as a constant. So that's a pretty simple concept. In the next video we'll take a look at declaring variables with the let or var keywords.
let and var for Variable Declarations
Let's take a look at destructuring objects. This has a slightly different syntax that destructuring arrays. We'll create a simple object called car, setting id to 5000 and style to convertible. Then we'll create two variables, id and style, and notice the destructuring syntax for objects. Instead of square brackets like we used on arrays, we're working with objects so we use curly braces to destructure an object. We'll take the id value of car and that'll get assigned to the variable id. Likewise the style property of car will get assigned to the variable style. We log out id and style and we get 5000 convertible. So again, if you're destructuring arrays be sure to use square brackets. If you're destructuring objects, be sure to use curly braces. Let's look at another example. So we have our car and we're declaring id and style, but we're not initializing them yet. We want to initialize them later in the code. So we use the curly braces specifying the id and style variables equal to car. So this looks like it should destructure into id and style, but we get an error. The reason we get an error is that is that the curly brace is also used for code blocks so the compiler is confused. Are we starting a code block or are we trying to destructure an object? So in this case we have to do something slightly different and here's the solution. We put the destructuring statement in parentheses. That solves the problem. We log out id and style and we get 5000 convertible. So we don't have this problem with destructuring arrays and we also don't have the problem if we're declaring and initializing variables at the same time, but in this case where the destructuring comes after any declaration, we need to use parentheses. Let's see a demo. So here we have our car variable. It's an object with an id and a style and we destructure car into two new variables, id and style. We'll log out id and style. I'll save this and we get 5000 and convertible. Let's not initialize our new variable's id and style and let's attempt to do the destructuring later in the code and you can see from the red squiggly that we will get an error if we try to execute this. I'll save it and we get our unexpected token error. Let's surround this with parentheses and I'll save it and everything's fine. Five-thousand convertible. So just remember to use the square brackets for destructuring arrays and use the curly braces for destructuring objects. In the next video we'll take a look at spread syntax, which is actually the opposite of rest.
Common Type Conversions
We often need to convert from one type into another type and there are several common ones that we use all the time. Let's take a look. So how do we convert any object or variable to a string? Well we can take the variable or constant and call its toString method and that's very straightforward and used often, but if we want to convert a string to say an integer? We use the built-in number object and there's a method on that called parseInt for parse integer. We're passing it a string 55 and the result is a number, 55 as a number. And what if we add a string, but we wanted to convert that into a float? Again we use Number.parseFloat, passing it the string. In this case we'll get 55.99 as a number and there are many other types of conversions you may want to do, but I found these to be the most common. Let's do a quick demo and see them in action. Let's parse an integer. We'll execute Number.parseInt and we'll pass it the string 55. I'll save it and we get the integer 55. If you want to be sure about that we can use typeof. I'll save it and we get number. Now what if we had extra characters in our integer? Let's say instead of 55 it was 55ABC. I'll save this and we still get 55. So as soon as we run into a character that's not part of the integer, parseInt stops parsing and we take what we've got, 55. Likewise if we call parseFloat and we'll say 55.88ABC, I'll save this and we get 55.88. What happens if we had extraneous values at the beginning like ABC before our 55? I'll save this and we get NaN. So would we call parseInt or parseFloat on number? We just need to make sure that it actually starts as a number. It doesn't necessarily need to end as a number. So that's all we have for converting types, but in the next video we'll take a look at some of the advanced features of loops.
Hi. My name is Mark Zamoyta and welcome to this module titled Operators. By operators we mean the simple mathematical operators plus, minus, multiply, divide, that kind of thing, but there are actually many more different types of operators. Let's see what we'll cover in this module. We'll start off by looking at equality operators, comparing if two numbers are equal or unequal. We'll look a unary operators. Those are operators that work on a single value or variable. Logical operators are also sometimes called Boolean operators and they result in a true or false value. Relational operators are things such as greater-than, less-than and so on, but we need to look at how relational operators work with strings. We'll take a look at the conditional operator, which is a shortcut for an if statement, an else clause, and we'll look at assignment operators. These are shortcuts which let us easily modify a variable in a concise syntax. Finally we'll take a look at operator precedence and this is very important. We know that operators such as multiplication come before addition and not knowing that rule is the cause of many bugs. So we'll take a look at the Mozilla developer network where we can find a table of operator precedents that can be used as a reference as we code. So let's get started and look at equality operators.
Let's take a look at unary operators. These operators operate on a single value or variable. The double plus sign increments a variable. So if var1 was equal to 5, after this executes var1 would be equal to 6. We can also place this operator after the variable name. Variable 1 will get used in some kind of expression and it will only get incremented after its use, but with ++var1, var1 will be incremented before it gets used in an expression and we'll see an example of this shortly. Likewise we can have --var1. The -- is the decrement operator which will subtract 1. Likewise we can have that operator after the variable. Another unary operator is the + symbol. That's not used often, but it could convert a string into a numeric type and the - operator changes the sign of a numeric variable. If var1 was -5 it will now be 5. And we'll see an example of that as well. So here we have a variable called year and we're setting it to 1967. What if we log out ++year? I'll save it and we get 1968. So it added 1 to year and then logged it out, but if we placed the ++ symbol, the increment operator after the variable, I'll save this and it prints out 1967. So the variable year was used and only after it was used in this expression was it then incremented. If we log out year next, I'll save it, you can see that the first log statement resulted in 1967, but year was incremented. Year was set to 1968 at the end of this program. So it's very important to keep in mind whether this operator comes before variable or after the variable and the decrement operator works much the same way, only it subtracts 1 from the variable. Let's look at the + operator. If year was actually a string here and let's print out the type of year, you know type of year would be a string as it is here. We get string, but if we added a + symbol to it, we get the conversion and it becomes a number and it's important to note that this + symbol does not make it positive. If this were a negative year, I'll save it and we still get a number, but let's see what value we get. We still get -1967. If we wanted to negate a variable we would use the - sign. I'll save it and now we get +1967. If 1967 as a string were positive, now we get the opposite, -1967. So again these unary operators operate on a single variable or a single value. In the next video we'll take a look at logical operators.
Logical (Boolean) Operators
In this module we looked at the equality operators. Those are double equals, triple equals also known as identically equal to, and then not equal to and not double equal to. We saw that the triple equal sign as well as the not double equals sign do not perform a type conversion. If you're comparing values of different types the result is false. We looked at unary operators. Those are plus-plus to increment a variable, minus-minus to decrement a variable, plus which is usually used to convert a string to a number, or minus which flips the sign on a number. We looked at logical operators, also called Boolean operators and those are and, or, and not. And it's important to know that and takes precedence over or. We looked at relational operators. For strings you need to keep in mind that capital letters come before lowercase letters in the ASCII table and the way to get around this is to convert your strings to uppercase or lowercase before using a relational operator on it. We looked at the conditional operator. We have a condition, which we usually put in parentheses, the question mark, our true-value : false-value. This is a shortcut for an if statement. And we looked at assignment operators. Those are +=, -= and any other operation followed by an equal sign and we also saw some operators that work with shifting bits such as less-than-less-than-equal-to to shift the bits left and greater-than-greater-than-equal-to to shift bits right. We wrapped up the module by looking at operator precedence. We saw how to find the precedence table on Mozilla developer network and we saw how it could be used when we're unsure about precedence. So that wraps everything up for operators. In the next module we'll take a look at functions.
Functions and Scope
Normally when a function executes it runs through all its code and then completes. All of its variables go out of scope, all of its functions go out of scope, but sometimes we want that function and its variables and nested functions to hang around and that's what a closure is. Let's see how we can use a closure with the IIFE pattern we just learned. So here's our IIFE, we'll create a variable carId setting it to 123, and we'll create a function, assigning it to getId. This function returns carId. Now of course carId isn't declared here so it'll reach to the parent function and get carId right here. And here's how we create a closure. We'll return an object where the property is getId and its value is the function getId. We could've named the property anything, but usually you'll see the property name and the function name; they will be the same. But now this object will get assigned to app and down here we'll log out app.getId and this will return 123. Let's go to the code and walk through this a bit. Here's our code from the slide and let's see what happens when we call app.getId. I'll save it and we get 123 and it's important to know how we got this value. Our variable app gets set to the return value of the IIFE and that includes a reference to our function getId and as long as we hold on to this reference or this function, our IIFE will persist. Not only will the function persist, but its parent function will persist along with all of its variables. So when we call app.getId this getId gets executed and this carId gets looked up. It gets found in the parent function right here. So that's the value of a closure and an IIFE. Any variables declared in the IIFE will persist along with any functions. You just need to make sure that you return a reference to the function like we do right here with getId. In the next clip we'll take a look at the this keyword, which is an important keyword that we use within functions.
The this Keyword
call and apply
Objects and Arrays
The subject of prototypes is very complex so we're only going to cover the basics in this course and we'll cover the most common use for prototypes. Before we use a prototype property, let's take a look at the last slide we saw in the prior clip. Here we have our car constructor function and it has a property carId and a method start. The fundamental problem with an object like this is that if we created 100,000 car objects this function would be replicated 100,000 times because it gets created right here in the constructor function. We don't need 100,000 copies of that function. We just need one and that's where prototypes come in. A prototype exists directly on car as a function. Here you can see that our constructor function is much simpler. It only has the carId property here, but now we're working with a prototype. Car has a property called prototype and we can go ahead and add our methods directly on prototype. So here we're creating a start method. We'll set it to the function where we simply log out start: this.carId. So now we can go ahead and make a million car objects if we want to, but there will only be one function and this saves a lot of memory. The only thing to keep in mind is that we still need to work with the function's context which is this. So we reference this.carId. When we create a new car and assign it to the car variable, we can go ahead and call car.start and we get start: 123. So by working with this prototype property of car, we can add our methods directly on car and use them on any object.
Expanding Objects Using Prototypes
Classes and Modules
Welcome to this course module named Classes and Modules. Classes give us the new syntax in order to create constructor functions. It's more similar to Java and C++ and C# and modules is a way to organize our code. Generally we can break our source code into a set of files and each file will become a module. We'll start of by covering the class basics. How do we create a class? Next we'll look at constructors and properties. We'll see how to add these to a class. We'll look at methods for performing code on a class and we'll look at inheritance. This is a technique where classes inherit from other classes so we don't have to do duplicate code. Next we'll create our first module and a module is a file that can be shared and imported into other modules. And we'll see how to import those modules and work with index.js and organize our code properly. So let's get started and look at how we can create a class.
Constructors and Properties
A constructor is a function that gets executed when a new instance of an object gets created. That's where a lot of setup occurs and that's where we start to work with properties on a class. Here's an example constructor for the class car. It looks a lot like a function. We pass it a parameter id and we'll take id and assign it to this.id. So we create properties using the this keyword just like we did with constructor functions. But now we're working with classes and their constructors. We'll instantiate a new car, passing it the idea of 123 and when we log out car.id that's what we get, 123. Let's see this in action. Here's the code from the slide. I'll save it. And you can see that we do get 123. The important thing is that we always need to be working with the this keyword. If we take that out, let's try to access the variable cid and assign id to that. We get a reference error; cid is not defined. So when we're working with constructors we need the this keyword in order to access properties. Now if we wanted to change this property while we're executing code, let's go ahead and set car.id to 456. I'll save this and now we get 456. So this is only used within the class itself. When we access the object we can reference the property directly, car.id. In the next clip we'll take a look at methods.
Methods are functions that exist on an object. Let's see how we work with them. Here we have the class car from before. It has the same constructor, but now we have a method and notice that we don't need a function keyword. We can just go right ahead and name the method and add the parameter list. In this case it's empty. We'll return Car Id: this.id. So again we need to be using the this keyword. That holds true for constructors and methods. We instantiate a new car with id 123 and when we call car.identify we get Car Id: 123. Here's our code and I'll execute it. We get Car Id: 123 and of course with methods we could pass in arguments. I'll pass it three exclamation points and we'll take that as a parameter suffix and I'll save this and we get Car Id: 123 and the three exclamation points. So just remember we don't need the function keyword. We can go ahead and just name our method and also we still need to work with this when we access properties. In the next clip we'll take a look at using inheritance.
Creating a Module
Importing a Module
We started off this module by looking at the basics of creating a class. We used the class keyword with our ClassName, which is by convention in uppercase and we give it a body with curly braces. We looked at constructors and properties and we saw that we always used the this keyword for properties. We looked at how to create methods and we saw how we could avoid duplicating code by using the concept of inheritance. The syntax for that is class and the class name Car extends. That's another keyword. To extend the vehicle class. And we looked at creating a module. Basically we export anything we need to use in another module. We saw how to export a class, but you could just as well export a variable, a constructor function, a regular function, or anything. And we saw how to use the import keyword in order to import something that's been exported in a different module. So now you know how to organize your code into classes and by putting each class in a file it can become a module. You export that class and import it wherever it's needed. In the next course module we'll take a look at programming the browser. We'll look at the browser object model and the document object model to see how to work with web pages and other features of the browser.
Programming the BOM and DOM
The window Object
The location Object
The document Object
Next we'll take a look at the document object which is used to program the DOM. The Document Object Model. The DOM is a huge topic so we're only going to cover it briefly here and here we have some of the common properties, methods, and on document. There are hundreds of these so you'll want to check out the Mozilla Developer Network, but some of the properties are body which refers to the entire body of the HTML page; forms to get a list of all the forms on a web page, and links to get a list of all the links on a web page. As far as methods go, createElement can be used to create a new HTML element and createEvent creates a new event to fire on the DOM. GetElementById singles out a specific element to retrieve from the DOM and getElementsByClassName will return all of the DOM elements for a passed-in class name. And for events we have onload, which fires after the document loads; onclick for a mouse click or a finger tap, and onkeypress when a key is pressed. And again there are hundreds of these properties, methods, and events so check out the Mozilla Developer Network to get a list of everything. In the next two clips we'll be looking at document in more detail, specifically how to select nodes and also how to modify nodes in an HTML document.
Selecting DOM Elements
Let's take a look at how we can select DOM elements out of our HTML page. Here are some of the common methods that we have on document to find an element. We can call document.getElementById, passing it the id of the element. And if we wanted to get an array of elements we call document.getElementsByClassName, passing it the name of the class we want to retrieve. And again this returns an array because multiple elements can have the same class name, unlike the id, which is supposed to be unique and document.getElementsByTagName will let us retrieve all the elements of a specific tag name. We could grab all the paragraph tags or all the h1 tags and there are actually many more methods to select DOM elements, but these are some of the most common. I added a few paragraph nodes to the DOM so that we can work with these in this clip. The first paragraph has a id of first and a class of p1 and the text First Paragraph. The second paragraph has a name, name1 and a class p1, and the third paragraph has a class of p3. So I'll make sure this is saved. So the first thing I want to select is the element with id of first, this paragraph right here. I'll say let el, el for element, = document.getElementById and I'll pass it the name first and let's log that out. I'll save it and we get our first paragraph right here. And now that we have that saved in the local variable el, e-l, there are all kinds of properties and methods we could access on that and we'll see that in the next clip, but for now let's look at a few different ways to select elements. Let's get all the elements which have a class of p1, specifically these two paragraphs right here. We'll call document.getElementsByClassName and we'll look for the class named p1 and I'll call it els because we're working with an array now. I'll save it and we get what's called an HTML collection, which acts as an array. We get our two paragraphs. If we wanted to see just the first paragraph we can subscript it. We'll say els subscript 0 and we get our first paragraph. Subscript 1 will be the second paragraph, and we see that here. And finally we can call getElementsByTagName and let's just search for the p elements, and we get an HTML collection of three elements. I'll open it up and here they are. There are a few other ways to access elements and search for them in the DOM. You can take a look at Mozilla Developer Network to find out more information. In the next clip we'll take a look at modifying one of these elements.
Modifying DOM Elements
We often want to modify DOM elements. We can change their properties, set up event handlers, and modify the visual aspect of the web page any way we'd like. In order to modify a DOM element we need to select the element first. Here we're calling getElementById, just getting a single element. Once we have it we can access a few properties or call some methods on it. To modify the text content of a paragraph or a div or some other element with text content we access element.textContent, setting it to the new string. If we wanted to add an attribute to an element, we call the method element.setAttribute, passing it the name of the attribute and the value for that attribute name. To add a new class to the element we call element.classList and classList is a property an element, but we access its add method. We pass it the name of the class that we want to add to the element and to access CSS information and to change that on an element, we access the style property. Here we're setting element.style.color to blue. Here we're calling document.getElementById and we want that first paragraph. We'll store that in the variable element. To change the content of the first paragraph we specify element.textContent and we'll assign a new string. I'll save it and new content shows up on our web page. If we wanted to add a new attribute to element, we could call element.setAttribute and I'll just make up a dummy one for now. We'll call it foo and we'll call it fooValue. That'll be the attribute's value. Let's also log out element. And here we see our attribute. Foo is set to fooValue and you'll notice that this element has a class of p1, but let's add a class of p2. We'll access element.classList and from that we'll call the add method. Let's add the class p2. I'll save it and now for class we have p1 and p2. A very common thing to do is to work with CSS properties. We can access element.style and then we can specify a property, in this case color. Let's set it to blue. I'll save it and now our first paragraph is showing up as blue. DOM programming is a very detailed subject. There are hundreds of properties, objects, and methods and events that you could use. See the Mozilla Developer Network for more information.
Promises and Error Handling
Error Handling Using try and catch
Developer Defined Errors
Creating a Promise
Settling a Promise
As I mentioned earlier, a promise represents a value that we don't have access to just yet. When we do get the value of a promise, it's referred to as settling a promise. Let's see the code for this. We're creating a new promise right here and we'll resolve it after 100 milliseconds. Notice that we're saving our new promise in a local variable called promise, lowercase. In order to get the value from our promise we execute promise.then. This is a function and it takes two arguments. They're both functions. The first function will execute when the promise is fulfilled. That means it resolved successfully and the second argument is a function that executes if there's some kind of error, if the promise gets rejected. Because of the asynchronous nature of promises, you might have to wait some time, whether for a timer, an HTTP call, or some other asynchronous event and you'll have to wait for that until one of these two functions get executed, but that's what promises are all about. They're about handling a success value or an error value from asynchronous operation. So here's the code from the slide. Notice that we're resolving the promise. I'll save it and you can see that we get fulfilled someValue. So the promise was resolved. The first function executed. What happens if we reject the promise? You can see it logs out rejected someValue so our promise has an error condition. It's rejected. Many times you won't need to create a promise. Many third-party libraries do this for us, but almost always when we're working with promises we need to execute the then function on that promise, passing it the fulfilled and rejected functions. Promises have many other advanced features and you can find out about those on the Mozilla Developer Network, but by calling the then function on a promise you can handle any success or error condition. Let's wrap up this module with a summary.
Data Access Using HTTP
HTTP Requests Using XHR
The first form of communication we'll look at is HTTP requests using XHR, and if we look at this acronym XHR, the H and the R stand for HTTP requests, but the X actually stands for XML and that was the popular file format when this was created. A lot of data transfer was done using XML, but things have gradually moved over to JSON. They're both text file formats and they both work equally well, but XHR is built into browsers and it's been in browsers a long time. Let's see how this works. To work with XHR we create a new instance of an XML HTTP request object and we set up an event handler. We want to handle the on readyState change event and if we look at this event handler, we see one of the key problems with using XHR directly. We need to be aware of the underlying protocol status result codes. We need to know readyState values and we need to know status values and because of this, XHR is rarely used directly. It's much easier to work with a library such as jQuery and deal with communication within promises, but if the ready state is for and if the status is 200, that means we got a successful response with data so we'll lot out this.response text. Now to actually make the call over HTTP we call xhttp.open. We use the GET method and pass the URL. And you can see here that I'm using mockapi.io. Let's just quickly go there. Mockapi.io is a web service that lets you work with HTTP calls with made-up data. I'll just sign in with my GitHub account and here's a problem we're using for this course and you can see that I have this users endpoint and this is the URL I would use, but if you wanted to work with a mock API, this is a great site to use. So once we have our URL all set up, we call xhttp.send. That'll send off the HTTP request and hopefully we get our return code as being successful. Here's the code from our slide and the only change I made was I put in the unique id number from mock API and I'm getting the user's data right here. So I'll save this and you can see that we did get a successful response because we have this large array now. We have user id 1 and all of its related data, user id 2 and all of its related data, and so on. And again it's not very common to work directly with this XHR technology. If we wanted to handle an error we would need to fully understand all the ready states and all the HTTP status codes. So in the next two videos we're going to stop using XHR and we're going to start using something much more common, jQuery. That way we can work with promises and things will be much simpler.
HTTP Requests Using jQuery
HTTP POST Using jQuery
Let's take a look at how we can use jQuery to post over HTTP. This would be used for posting a form or posting other information. We'll import jQuery as the $ and we need some information to post so we have an object literal and our user just has a name an avatar file. We're not posting the file, just the file name. And then we call jQuery as the $.post. We pass the URL and our data and we want to use this as a promise. We call promise.then, passing it our two handlers. The first one for a success and the second one for an error. Let's look at this in code. So here's the code from the slide. I'll save it and the promise resolves successfully. We log out data: and the data right here and that's what we get. You see the name and the avatar were set, but we're also getting back an id, id 11 and the date and time it was created at and that's important to know. When the server assigns a unique id we get that information back. And let's force an error here. I'll just add a z at the beginning of URL to invalidate it and I'll save it and now we have an error. So our promise is working fine. Again on a post we can't see it here. Let me widen the window, but on a post you need to make sure to send the data that you want to post as we see right here in the user variable. So that's all we have for data access with HTTP. For more information see the jQuery documentation on working with HTTP.
Preventing Form Submission
Accessing Form Fields
Showing Validation Errors
Security and Building for Production
Chrome Developer Tools and Security
Security and the eval() Function
Preventing Man-in-the-middle Attacks
Cross-site Scripting (XSS)
Building Your Application for Production
Summary and Course Wrap-up
Mark started in the developer world over 25 years ago. He began his career with a Bachelor of Science in Computer Science from St. Johns University. After spending 10 years on Wall Street working...
Released26 Jul 2018