What do you want to learn?
Leverged
jhuang@tampa.cgsinc.com
Skip to main content
Pluralsight uses cookies.Learn more about your privacy
Quick Start to JavaScript: Volume 3
by Susan Simkins
In this final Volume of the Quick Start to JavaScript series, we'll learn about objects, the core concept of an object oriented language like JavaScript. Software required: Brackets Text Editor, Google Chrome.
Start CourseBookmarkAdd to Channel
Table of contents
Description
Transcript
Exercise files
Discussion
Learning Check
Recommended
Introduction and Project Overview
Introduction and Project Overview
Hi, I'm Susan with Digital-Tutors, and this is Quick Start to JavaScript Volume 3. In this final volume, we'll learn about objects, the core concept of an object-oriented language, like JavaScript. We'll also learn what object-oriented means, and take a look at two different ways we can create objects in our code. We'll also learn about the concept of scope, and how it impacts our code, and learn about best practices like formatting, and using a linting tool to check our code for errors and inconsistency. So, with that, let's get started in our next lesson, and learn about objects.
Quick Start to JavaScript: Volume 3
Objects
In this lesson we'll learn how to create objects. In this volume we'll continue to work out of Brackets Text Editor just like we did when we finished up in Volume 2. So to open our files for this lesson we just want to come over here once again to our Files pane and we want to select our drop down arrow, come down to Open Folder and we also want to make sure we navigate to our project file for this lesson. So we're in Lesson 2 so we'll open 02Begin, select our folder and then we'll double-click on our main .js file. Should bring it up into our working files which you can find in our Scripts folder. So let's say we want to model something using our code or describe something. Lets say I'm drinking my coffee and I find the perfect combination of flavors and temperature and brand maybe and I want to remember this at a later date. Using the syntax we know so far how could we model something like my coffee which you can see right here. We have our little CSS coffee mug with a little coffee spill since that seems to happen to me quite often. So we might use something, we know we can use variables to store information so lets go ahead and use variables to kind of describe our coffee here. So we want to use that var keyword and then we want to give it a name. So maybe I want to call it variable coffee flavor. I'm just going to use camelcase for this. And then we need our assignment operator or equals sign to assign a value and then let's say my flavor is espresso so I add that in the form of a String. And then we'd add our semicolon. And let's say we want to describe its temperature so var coffee, whoops if I can type correctly, temperature... would be maybe piping hot. And then maybe I wanted something else like the perfect size I remember the amount of ounces I like in my coffee might be something like I guess it wouldn't be a String but a number, maybe 100 ounces or 1000, lots of coffee. And then maybe we want to remember, do we add milk to our coffee? We might finish up by adding one called coffee milk and then maybe we'd use a Boolean for this and maybe I like milk in my coffee so I might set that to true. So we have a collection of things that's describing our coffee but what if we wanted to use all of these together somewhere else in our code? Well, using what we know so far we could use something like an array but that doesn't quite make sense. What if we want to easily be able to pick out something that describes something about our coffee? Maybe I want to be able to easily refer to its temperature, the amount of ounces it has or whether it has milk? Well one thing we know about arrays is we have to reference an array position so that's not ideal if we want to remember a specific thing and be able to refer to it by name like we have here. And another downfall of this is we have no way of identifying that these belong together. These are all treated individually in our code and there's no association here between the relationship of our description. So the way we can model things like this using code is by creating whats called an object. So lets go ahead and create an object and see how we can accomplish the same thing in a slightly different way. So I'm going to press Enter here just so we can add some separation between our variables and our object. And just like with a variable we start by storing our object in a variable because that's really how we remember values or the things of our code. So we need that var keyword and then we want to give our object a name so maybe I want to call it my coffee since that's what we're creating here or describing. And then we need our assignment operator and if you think back to everything we've learned so far one way we've been associating code together as in this all goes together is by creating a code block and that's exactly what we do when we create an object is we just have some curly braces that tell our code that this all belongs to our object. And we add every description about our object in the form of what's called a property. So lets add a property which is going to describe our object. So lets say we wanted to describe the flavor just like we did with our first variable we just give it a name which is called a key when we're talking about an object. So we're going to add our flavor and then rather than using an assignment operator which is storing something we're actually kind of describing something. So the syntax is a little bit different here and we use a colon and then we want to add whatever value we want here just like we would with a variable. So the flavor we have is espresso so we're just going to go ahead and add that. And then we're not creating a statement like we were up here, we're actually describing a list of properties since our object is a list of key value pairs, a list of properties. So just like we would in an array we comma separate something like that when we're storing a list of values. So we add our comma and then we can add our next property. So maybe we want to add the temperature. And we want to describe it as being piping hot. We add our comma, add our next property. Say maybe we want to say ounces would be 100 and then maybe milk, we want to add true. And one thing you'll notice here is I didn't add a comma after our last value here and that's because if we add a trailing comma, so if we do't have anything after this then in Internet Explorer we're gonna get an error. So we just leave that last comma off just so we know that our code is going to work in those older versions of IE. So I'm going to go ahead and delete these extra spaces here and the last thing we need is a semicolon after our last bracket. So just like when we're creating a variable here and giving it a value we're doing exactly the same thing here. We're creating a variable, we're giving it a name and then we're storing an object in our variable so we have our variable and we finish it off with a semicolon. So what if we want to talk about the properties we added in our object? Well we can use something called dot notation to reference anything inside of here, any of our properties. So the first thing we want to do is use our name of our object, so mycoffee, and we can just add a dot and then whatever we want to access inside of our object. So we can see we have flavor, temperature, ounces and milk and our code is recognizing all these as properties and pulling it up as options when we talk about the mycoffee object we've just created. So maybe we want to find out or remember later how many ounces were in our coffee. It's going to say mycoffee.ounces and then add our semicolon here. So lets go ahead and use an alert to alert mycoffee.ounces. So just alert and then add our object and our property inside those parenthesis. And if I hit Control S to save this you can see over here we're getting an alert box with our results. We're seeing 100 which is exactly the value we have stored inside of our object. So I can say okay thank you for that little information and you can kind of see here how much different this is than trying to describe it in just a series of variables. These are in no way associated with one another. There's nothing in our code to indicate that we're describing our coffee and they're just kind of loosely floating around versus here we can easily talk about these by name. We can maybe, if we needed to know full list of everything inside of here we are able to do that. And things of that nature. So now that we have learned how to create our first object and how to access its properties in our next lesson we're going to learn another way of accessing properties in an object and also about something called a method.
Methods
In this lesson we'll learn about adding methods to an object. in our last lesson we learned about objects or how we can use this object syntax to model real life objects using code when we modeled our coffee here. So what if we wanted to add something other than a property or a pair of a key which consists of a name and then a value? Well we can add something called a method to an object which sounds like another complicated term to learn but all it really is is adding a property in which the value is a function. So lets go ahead and add a method to our object and see what this does. So since we're going to be adding another property to our coffee object here after last property, our milk and then our Boolean value of true we need to add another comma and then we just use the same syntax so we want to give it a key or a name and we're going to call this maybe reheat. Maybe we want to be able to perform a command that reheats our coffee if it's gotten cold. So lets just call it something common sense like reheat. We need our colon and then instead of a primitive value kind of thinking back to Volume One we remember primitive values are our most basic unit like a String a number or a Boolean. So for reheat we're going to use function as our value. So we're going to say function and we're not going to accept any parameters because we're just going to be reheating our coffee, it doesn't need to accept any arguments here. And then we need our curly braces. And inside of this, let's go ahead and think this out. So this purpose of our function is going to be reheat our coffee so we're going to say look at the temperature and set it back to be hot. But it doesn't make sense to run this if it's already hot. So first let's go ahead and put a check inside of our function to check our temperature and see if it's cold. So we're going to say if... and then our object so we want to say what are we targeting, if what is cold? So we want to tell it to look for mycoffee object and then we're going to be accessing a property of our object which we learned in our last lesson we could use dot notation. So first we want to name our object and then we just want to select whatever property we want to target, so we're going to chose this last one temperature so you could type that out or you could also select it from the drop down list it pulls up automatically for us. So you could also see that reheat here has now been added as a property of our coffee object. So I'm going to select that temperature. So if my coffee's temperature is equal to cold, then we need our second set of curly braces to tell our code what to do if it's cold and inside so we're going to use two spaces here to maintain that indentation and be consistent. We're going to say set it back to be hot again. So we're going to say mycoffee for our object and then what property we want to access so temperature, and set it to be piping hot again. So we use that single equal sign once again when we want to assign a new value to something and then we'll set it back to be piping hot. And then I'll add our semicolon and maybe also we want to have an alert here so we know that our function is working. So maybe we want to say if our coffee is now hot again and this function has been run then alert your coffee has been reheated and then our semicolon right there. And so lets go ahead and hit Control S to save this and you can see we get some issues down here but we're going to come back to these once again later in our course and learn what JSLint is. So I'm going to go ahead and exit out of this and right below here we're going to, first we need to set the temperature back to cold so we can see our function is working. So we're going to say set mycoffee, so our object, and then our property set it to cold using our single equal sign or our assignment operator and now it's cold but if you remember we need to invoke or call a function in order for it to run. We actually have to use that command to see that code being run so we want to use our command so we want to say mycoffee.reheat and then when we call a function or invoke a function you remember we need to add our parenthesis there like we see right here. Since we do't have any arguments we don't have to add anything inside so we just need our semicolon. So if we hit Control S to save we should be seeing our message that our coffee's been reheated. So I'm going to hit Control S to save and you can see that our method, our reheat method of our mycoffee object is now working. So this is really really cool. We've learned how to associate a function with a specific object which is called just a method. It's correct to call it both a function and a method but a method is more specific because by implication of using that term you understand that a method is associated with a specific object. So it gives it a better idea of the context and we want to make sure to use that term if it's inside of an object like we have here. And it turns out we've been using methods all along so for example, when we use console.log, log is actually a method of the console object. So there are already objects that have been created in our code. There are already things that are built into the language or things that have been created by the browser such as the console object. That way we already have things that we can use and we don't have to write it from scratch ourself. So this is really really cool, we've actually been using it all along and not realizing that we've been using objects and methods this entire time. So we can see console.log, we have our console object and then dot and then our method which we can tell is a method and not a key and just a primitive value pair because we get those parentheses there showing it is a function or a method. So this is really really cool and if that kind of threw you for a loop as we were going along wondering why we could use some functions without this little word and then a dot and then some needed it like our console.log and our mass.random, that's because they are associated with an object so we have to specify that object first. So now we've kind of come full circle and we can really understand what that is. And if you remembered in our last lesson we learned about dot notation I also mentioned that there's another way of accessing a property of an object as well. So if we wanted to say mycoffee.temperature and assign it cold as a value instead of piping hot we could use something called bracket notation instead. So right under here I could also say mycoffee is our object and then rather than using that dot there we use brackets notation. So we need straight brackets and then we add our property inside in the form of a String. So we'd say temperature and then our closing bracket and then we need our assignment operator and we can add something different like lukewarm maybe. And so now if we run this we shouldn't get our function working. So I'm going to hit Control S to save and you can see we're not getting an alert that our coffee has been reheated because first we've changed it to cold and we've also changed it to be lukewarm. And this syntax might be a little bit confusing looking but we can also kind of think of an object being similar to an array because an array if you remember from Volume 2 is a comma separated list of values. So an object is a list of key value pairs so we can access a property similar to how we would target a position in an array. Maybe if this was an array we might have mycoffee and then we use this straight bracket notation and maybe if we wanted to access temperature we would put in one there. If you remember, array position starts at zero so we'd have zero and then one. Now since this is an object this notation doesn't work but you can kind of see the similarities to that. So now that we've taken a look at objects, we learned about methods and also taken a look at some methods and objects we've been using this entire time in our next lesson we're going to continue to learn about objects and talk about a way to create multiple objects using the object constructor.
Object Literals and Object Constructors
In this lesson we'll learn how to create objects using an object constructor. Lets say we have our friends back from Volume Two. Lets create an object to represent our friend Mark using code. So if we wanted to represent him using an object we just use our var keyword, give it name like Mark and then use our assignment operator and open and close our curly brackets at our semicolon and add all of our properties and any methods we might need inside. So looking at Mark how can we describe him using our code? Just by looking here at our friend Mark there's two things I can really tell about him. I can tell that he has a name and also what color his shirt is as well. So lets add his name as a property. So I would say Mark's name and then a colon and then whatever value I want for that property. So his name is Mark. Then I add a comma and add any other properties we need, so if we wanted to say his t-shirt color we just say t-shirt color and then maybe that is something like navy blue. And since that's all we can really tell about him just by looking I'm just going to leave it at that. And remember if we have a list of properties inside of our object we don't add a trailing comma after our last property because it will throw up that error in older versions of Internet Explorer. So we go ahead and leave it off that way we can make sure we don't run into any of those errors. So I'm going to go ahead and delete the extra space and if we were to do the same thing for Lisa we might see something similar. Maybe we create our object for Lisa and then we'd add her properties inside so her name is Lisa and her t-shirt color would be something like red. But as we're objectifying our friends in a good way with our code I can see something in common between our objects. We can see that our friends have names and they have t-shirt colors as well. And if you think back to Volume Two, one principle we talked about was called DRY or Do Not Repeat Yourself when you're writing code. So when we're creating objects in this way we're creating what's called an object literal or creating and defining our object at the same time which is called creating an instance of an object. So lets look at another way we can create an object and see how this might be a little bit different than using an object literal. So right below here we're going to create what's called an object constructor which uses a function to create kind of a template for an object. So if you remember we create functions using the function keyword then we need to give our function a name and when we're creating an object constructor or a function that creates objects it's best practice or standard to name it with an uppercase letter. So if we wanted to create our constructor representing our friends it might make sense to call it something like Friend and make that first letter a capital letter. So we're going to call this Friend. Add our parentheses which is where we'll be adding our parameters, and then open and close our curly brackets. So since we're creating a function that's going to be creating our objects we need to add our properties that it's going to be creating each time we call it inside. And rather than adding our properties as a comma separated list like we do in an object literal we have a special keyword that refers to the object we're creating and that's called this. So rather than saying name which only refers to the Lisa object since we're creating a template here the this keyword is going to refer to whatever we create using our function. So it's a more general way of using or creating properties and our object constructor. And this will make more sense in a couple minutes when we start creating instances with our constructor we'll revisit this kind of concept. So we're going to use the this keyword. We'll say this.name for object is going to be a name. And this is going to be a parameter so we need to add it inside of our parentheses and then we need our t-shirt color so we'd say this.tshirtcolor is going to be tshirtcolor and then we need to add this as a parameter as well so I'm going to add that comma and tshirtcolor. So now we have a function. It's going to expect a name and a t-shirt color as arguments and then it's going to create an object and set the properties to whatever values we pass through the functions. So if we wanted to create an object for our friend Denny we could say var denny. Use our assignment operator and instead of listing our his properties one by one like we did with our object literal we're going to use our constructor and we use a new keyword to create an instance of our constructor. So we can say Denny is a new and then we're going to use our constructor so he's a new friend and then we need to add our arguments in parentheses. And you can see it's already pulling up for us the arguments it expects to see. So you can see it expects a name and a t-shirt color as well. So his name would be Denny and we'd add a comma and his t-shirt color would be green and then we can add our semicolon. So just to kind of test this out and see if this is working we're going to use our alert command and say what object, so Denny is our object and go ahead and tell us his name using that dot notation. So if I hit Control S to save then we should see his name alerting in a popup box in our browser. So I'm going to hit Control S to save and you can see that it's returning the name we passed to Denny. So what this is doing here is when we're using our constructor we're basically just invoking a function or calling a function that is creating an instance of our friend template or our friend constructor. So it's going to take our argument so for example we pass through Denny and it's going to say Denny's the name so I'm going to create a property for Denny and I'm going to set this .name to be Denny. So in effect as it's going through our function here it's saying our object so set denny.name to be Denny and then it's going to set out object denny.name the t-shirt color, excuse me, to be green. But by creating our constructor we reduce all that repetition in our code. So if we wanted to very quickly and easily be able to create objects for all of our friends we could just say var Lisa is a new friend, so we could say Lisa and then her t-shirt color would be red and we get the same, whoops if I can type correctly, the same end result as we do with our object literal but we can reuse this as many times as we want and avoid any kind of repetition in our code. So now that we've taken a look at objects constructors and how we can reuse them to create prototypes or templates for an object in our next lesson we're going to continue to talk about objects and learn about object oriented programming.
What is Object Oriented Programming?
In this lesson we'll talk about object oriented programming. When people talk about JavaScript as a language you'll often hear them refer to it as being object oriented. So what does it mean when we say that JavaScript is an object oriented language? One way we have of writing code is procedural. So when we create a list of step by step instructions our code is run from top to bottom and we can say this is a procedural way of running code. Compare this to an object oriented approach in which we create objects and the objects themselves pass code back and forth amongst one another as needed. So when we say that JavaScript is object oriented we mean that it really revolves around this concept of objects and how code moves back and forth between objects. So we take a thing or an object and we describe it using code. We describe its characteristics as properties and we describe its actions as methods. And we have two main ways of creating objects in JavaScript. We can create what's called an object literal in which we define and create an object at the same time or create an instance of an object or we can create what's called an object constructor in which we define a template for an object or an object prototype. From our prototype we can create as many instances of our object as needed. And we have three different kinds of objects in JavaScript. We can have Host Objects, Core Objects and Objects defined by the coder. Host Objects are objects that are defined by the environment in which our code is run. So if we're writing JavaScript for the web a web browser would be our host environment. The following is a list of a couple examples of objects defined by the browser. Most of these you won't recognize but console is a host object that we've been using all along. One downfall of using host objects however is if our code is run in a different environment other than a web browser if it depends on an object that is defined by the browser then our code is going to break because it's only defined within that environment. We also have core objects as well. Core objects are objects that have been defined or or built into the JavaScript language itself. So we get objects like Math, which we've been using all along, methods of the math object to use math.round, and math.random. We also have other objects like Object, String, Boolean, Array, Date and Number, and many, many more besides, that come with their own sets of properties and methods built into the language itself for us to use as needed. Anything else that's not a core object or host object is defined by the coder as needed, or if we're using a JavaScript library, like jQuery or Angular JS, we also get objects defined by those code bases as well. So now that we've taken a look at object oriented programming and studied the nature of objects themself, in our next lesson we're going to talk about the global object in context of our host environment, the web browser.
This and the Global Object
In this lesson we'll talk about this and the global object. A couple lessons back when we learned about creating our own object constructors, we learned that we could use the this keyword to refer to the instances of the object we'll be creating. So what happens if we were to alert this outside of a constructor? Well, let's go ahead and see what happens. So I'm going to use the alert function, and we're just going to alert this. So we probably expect this to throw out an error, but if I refresh the page, here, we're getting something really interesting. You can see it's returning a value of a type object, and it's also returning an object called Window. And this is really interesting, because our code is actually being added as properties of what's called a global object. And we always have this concept of a global object in our code, but that depends on what kind of host environment we're writing our code in. So since we're writing our code in a browser, that global object is actually the browser window itself. But why is this actually important to understand? Well, let's write some code and we can get a better idea of what this does, what this means for our code, and what we can do with it. So I'm going to press OK right here. And let's say we create our own function. I'm going to go ahead and delete all of our code, here. We will write a function that says hello. And all it does it is just alerts, hello. Well, if we run our code here, woops, I'm just going to press our live preview so it's connected there with our ELO lightening bolt. If we invoke our function and run it, you can see we get our result Hello. But since we're actually writing our code, and all of our code becomes properties of that global window object, we can also use this as a method of the window object and we should see the same result. So if I say window.sayhello, we still get the exact same thing happening. If we say window.alert, hit Control S to save, you can see it still works because truly, all of our code is being added as properties of our window object. And to get a better idea of what our window object actually is, if you remember in our last lesson we talked about how JavaScript revolves around objects, uses this concept of objects to model real life objects. I'm just going to open a new window here, pull up our developer tools using F12, and if we type in a method of window, I'm going to just use one we haven't learned about called close, which will close the window. If I run this by pressing Enter, you can see our tab close. So just so we can see this once again, I'm going to go ahead and re-type that out, just window.close. As I press Enter, pay attention here to our tab. So I can press Enter, and you can see it enclosed our entire tab or entire window. So we can really see that all of our code is running inside of our little window environment. So if we were to do something in here like create our own function, maybe we wanted to call it alert, and we wanted our alert function just console.log hello, whoops, if I can type that correctly. Just like our other function, here. If we were to call this, now, do you think we will get our alert pop-up box like we normally do, or will we see something else? If I go ahead and hit Control S to save, and make sure this is running, you can see that nothing is happening. Or, at least what we expect to happen normally with our alert function is not actually ocurring, because if I pull up F12 to see our Developer Tools, you can see that we're getting our message log to the console hello rather than seeing our pop-up box. And this is because we've accidentally overwritten the existing function called alert with the functionality we've added to this function instead. So when we're writing code in what's called a global scope like this we have to be really, really careful that we're not accidentally overwriting code that's already there. So we can think of this as being really similar to if we were to create a variable in our own code, and maybe we call it example, we give it a value, and then further down in our code maybe we forget we use a variable with the same name, and we set it to a String. Then if we were to alert our variable, I'm going to go ahead and delete the code we created up there. So if we alert our variable example, we can expect to see example and not to, so I'll hit Control S to save, woops, making sure we're in our text editor and not the browser, and refresh this and you can see we're getting example, and not to, because the further down our code is when we have a conflict, it's going to overwrite previous code that does the same thing, so since it runs from top to bottom we can easily overwrite things we've already created. And to help understand this better, we need to get a better idea of the scope of our code. So that's exactly what we're going to talk about in our next lesson, when we talk about local and global scope, and how it affects the code we write.
Local and Global Scope
In this lesson we'll talk about local and global scope. In our last lesson, we learned how all the code we've been writing directly in our file has been global in scope. And beyond that it also is added as properties of our global object. So, since we're writing code in the context of the browser, or the browser is our host environment, that global object is the window object. So let's go ahead and take a closer look and see what it means to have code that is global in scope. So, I'm going to go ahead and create a variable here, and I'm just going to call it example, and then, let's just give it just an example value here. So we've just created a global variable just by typing it into the root of our document, here, and let's go ahead and just alert our value, here, so alert our example variable. If we hit Control S to save, you can see we get our value inside of our example variable, just as we expect. So let's add this inside of a function and see if code inside of a function has access to our global variable here. So I'm just going to create a function called alertExample, 'cause it's just going to alert our example variable here, and hit Control X to cut this, and paste it inside of our function, and then we just need to invoke it. So, do we think our function, here, is going to have access to our global variable? Well, let's go ahead and run this and find out. So I'm going to hit Control S to save, and you can see we have exactly the same result. So yes, our code, our global code, is available inside of functions, and, in fact, it's accessible from anywhere in our code, which is why we have to be so careful when we're creating code that's global in scope, because it's very easy to accidentally overwrite something, or have other code overwrite something that we didn't intend, so it's really important to understand when our code is global. So I'm going to go ahead and press OK here, and let's add another variable inside of our function, here. So I'm going to create a variable, let's just call it another Example. And then we can give it any value here, let's just give it a question mark for now, and let's see if we can access our variable outside of our function here. So we're going to alert it, which means, or invoke it, meaning our function will be run and this variable will be created and so after this happens by invoking our function let's try to go ahead and alert our variable inside of our function. So I'm going to go ahead and hit Control S to save, we can see we're getting our example value, so it's alerting our initial global variable. So we can press OK, and then we can see that nothing is happening. So when we're adding variables or creating variables inside of a function, what's happening here is we're creating what's called a local variable. In JavaScript, new scopes are created every time we create a new function, so it has function-based scope, and every time we create a function, all of our code inside is going to be local to that function itself, meaning it's invisible outside of that code. So that's why we're not able to see this variable, it's not recognizing it as existing, becasue it can't see inside of our function. But conversely, when we have global code, it can see anything in that global scope, so our function can access code outside of that function. But it's also really easy to accidentally create a global variable inside of a function, and the way we would do this is if we forget to use our var keyword. So if we just said another Example and then we declare it without that var keyword, if we hit Control S to save, we're going to get value, and then we're getting a question mark as well. But this is very, very bad practice. We want to limit our global code as much as possible, because we have this ability to overwrite existing code and that's kind of messy and sloppy, so we will always want to use that var keyword any time we declare a variable and we also want to be as careful as we can with a scope of our code. For example, if I press OK here, and I have named this Example, we can see we have two variables called Example, and let's see which one is going to be alerted. I'm going to hit Control S to save, and we get value, because our alert is before our second value, but if I hit Control X here, and paste it after, and run this again, you can see we're getting question mark. So we are initializing a variable right here, and then we're changing its value to be our question mark String here. So we've overwritten our initial value, and if we were careless and we didn't know this was happening, we might expect to see this instead. So, now that we've taken an initial look at global and local scope and started to see how our code can access code depending on its scope, in our next lesson we're going to continue talking about scope and try to gain a better understanding of global and local, and the differences between the two scopes.
Understanding Scope
In this lesson, we're going to continue talking about the concept of scope. In our last lesson we started talking about this concept of global and local scope, and we learned that code we add inside of a function was local to that function, meaning it's invisible to the outside code. So let's go ahead and take a more in-depth look at this concept of local scope. So we're going to go ahead and create a function, here. So I'm just going to call this function, maybe we're going to alert a Number. And then let's go ahead and declare a variable inside, so let's say this is var one, and then we're just going to give it a value of one or a String of one. Or I guess we could just add it as a number, as well. And then we're going to just alert that Number, so we're going to alert our one variable, and then we just want to finish by invoking our function, so just alert, Number. And if we hit Control S to save, then we can see we're getting our value of one as we added inside of our var one. We also saw in our last lesson if we try to alert a variable that's local to a function, that we had something kind of funny happening, so if we add an alert, and we want to alert that one variable, just like we did inside of our function, we hit Control S to save, we can see we get one once, but we don't see it the second time because this variable is local to our function, meaning our code outside of that function has no idea that that code exists. It's completely invisible to the outside code. So if we didn't understand this concept of scope, and we were trying to use variables we created inside of a function, we might be kind of confused and frustrated as to why this second alert doesn't work. But luckily, since we're taking a look at this and we're starting to understand scope more, now we can understand that our code inside of our function is local, which is why this isn't working. So let's go ahead and add a function inside of our initial function, here, and take a look and see how the scope may or may not change. So I'm going to go ahead and delete this, and inside of our function I'm just going to add a couple spaces here so we have plenty of room, and let's say we have another function, and we're just going to alert AnotherNumber. And inside of here we have another variable, and let's just call it two, just so we can kind of keep these straight a little bit in our head. I think numbers are a bit easy to think about rather than random words, here. And we just want to alert our second variable, so we're going to alert two. And then we want to finish by invoking our function, so right below our function, we're just going to invoke it by using our parentheses here, in our function name, so alert AnotherNumber, and if we hit Control S to save we see we're getting one, and then we're getting two. So just like we saw out here, if we tried to create another variable, let's say we have var three, and it's three. Let's go ahead and add this at the top, so before our function. I'm just going to add it on line one, so we have our global variable three, if we had tried to use our global variable inside, if we go ahead and run this, we can see we get one, two, and three, because our initial variable is global. So what if we try to access one, inside of our inside function? Well, let's go ahead and see. I'm going to go ahead and alert one. And just kind of take a second and think whether you think this is going to work, or maybe whether it's not going to work just like when we tried to alert one outside of our function it didn't work because this one is local to our function here. Well, if I press Control S to save, to run this, we can see we get one, we get two, we get three, and then we get one again, and that's because our inside function does have access to the code in our outer function, just as if this is global in scope. So although this is not global in scope like our three, inside of this function we can kind of think of all the code right here, so all the code initially added in here is kind of being global to this function itself. But what if we try to use our variable inside of our second function, here? So, if I come down here and I try to alert two, do we think this is going to work? Or do we think it's not going to work, like if we trying to come down here and we tried to alert two outside of the function itself? So, if I hit Control S to save, we can see we get one here, we get two, we get three, then we get our one, but our last alert, here, if we press OK, we can see is not going to work, because our two variable is just local to this function. So it's invisible to the outside code, because we created a new local scope. So what this means is every time we create a new function, we're changing the scope of our code, and all of the code inside of that function is local to that function. So everything inside here is local to this function, and can't be accessed outside of that function. If we added another function inside of this function we'd be creating a new scope as well. But to understand what code has access to what, we want to look for the outer function if there is one. So we have access to all the code in the outer function, inside this function, so we could use one, like we saw here, our alert one worked, and we have access to all the global code, outside of this function, so there's no other function outside of this, so all that code is global and can be accessed from anywhere in our code. So just to go over this one more time, when we're trying to think about the scope of our code, we have our global code, so anything we type directly in our file that isn't inside of a function, and then every time we have a function we're creating a new scope, so all that code inside of that function is local to that function. And we see the same thing every time we create a new function all of our code is local to that function itself. Which can be kind of confusing at first, but as you go through your code and you use it more and more this concept will become much more intuitive. And you might be wondering how you can protect your code as we saw before, when we have code that's global, it's very easy for that code to be changed in ways we didn't intend, or to overwrite something you didn't mean to. We can protect that with something called namespacing, which is outside of the scope of this course, but we'll revisit that fact later and for now you just want to be able to understand how the scope of your code is changing as we're writing it, when we're creating little small bits of code like we are now, it's most important just to be able to understand what the scope of your code is. Is it global, is it local? If something isn't working, is it because it's not inside of the correct scope? So, now that we've taken a more in-depth look at understanding scope, in our next lesson we're going to talk about some common conventions in JavaScript like tabs versus spaces, and also learn about JSLint.
Coding Conventions and Using Jslint
In this lesson we'll talk about the importance of coding conventions and also learn how to use JSLint. Up until this point we haven't been really strict when we're typing out our code with certain things like how many spaces we use to create an indentation, or whether we use the Tab key instead, or the little small things here like whether we add a space between our parentheses and our curly brackets, and things of that nature. But as it turns out, these little small details are pretty important when it comes down to it. Especially when we have other people reading and working with our code. So one thing we can do is stick with a coding convention so we know exactly how to format our code and make sure that it's following kind of a universally-accepted standard. And one way we can check our formatting is to use a Linting tool like JSLint, which is this little thing at the bottom that's popped up throughout the course, and I kept on saying we'd come back to it later. A Linting tool is awesome for code, because not only does it check for common errors for us and catch those and look for little sloppy mistakes that JavaScript will let slide sometimes, but it also helps us focus on consistency in our formatting. So we're going to go ahead and take a look and see how we can use JSLint. Which, we'll see some really funny erros here, and at first it's not so important to get every error gone as it is to understand that consistency is important and to aim for that consistency in our code. So I'm going to go ahead and pull up JSLint, which is built in, right into brackets for us, which is really, really nice, and we can just click down on this little exclaimation point right here. So if we pull it up, we can see we have quite a few erros here in our code, and even though our code is running, these are considered problems in our code. Maybe, it doesn't mean that our code is not working, it just means that there are things we could do in a better way, so on line one we have this little message here saying alert was used before it was defined. Which is confusing because we know alert works. It's worked all the way up until this point just fine, so what does it mean that it isn't defined? Well, what it's checking for is things that are built into the language, so our core objects, our core methods, things like that, so if we use something that's a host object, or something that's built in to the browser environment, then it's going to throw up this little problem here. So if we use it as a method of our environment, then we should see that going away. So alert isn't a core function, it's a method of the window object, and we can get in the habit of using it as such. So if we type in window.alert, and hit Control S to save, we can see that little error going away. The next thing we can see on here is a problem with spaces. We haven't been strict about the way we type in functions and things of that nature, but the way JSLint likes things to happen, is it likes to have a space here between our parentheses and our curly brackets. So just like this, we have our parentheses right after a function, and then a space between our function name and our curly bracket, so if we hit Control S to save, we can see that goes away. For our next problem we have an unexpected space. And if we click on the error, by the way, it'll take us to where the error is, which we can see we're getting an error here, but that's okay 'cause we have errors in our code on purpose. So if we click on this we can see we have an unexpected space it sees right here, but we can't see that unexpected space, so if we turn on what's called Whitespace, we should be able to see everywhere we've used the space key on our keyboard to add in a space. So if I come up here to View, I can turn on show Whitespace, and we can see all the spaces in our code, which, I believe was an extension I added. So if I come in here to our Extension Manager, if this loads, you can see I have an extension called Show Whitespace, so if you come over here and search for "Show Whitespace," you should be able to click on this button to install it, and add it to brackets for you if you want to be able to do this as well. So if I hit close, we can see this little extra space here, this trailing space, which is unnecessary, so we can go ahead and delete it, hit Control S to save, and we can see that error going away. The next thing here, we see, we have a missing use strict statement and what this does is it forces a strict method of Linting on our function itself, so it's not going to let us get away with any kind of little sloppy habits such as right below here, you can see we've used a variable before it was defined. If you remember we declare a variable using that var keyword, so if we use it like this, not only are we not creating our variable before we use it, we're also creating it as a global variable when we use it without that var keyword which we saw a couple lessons back. So, first thing we want to do is use that strict statement, which is just a String that's used strict, and then our semicolon, so if we hit Control S to save we should see this go away. And then, now we get this error randomNumber was used before it was defined, so we just want to go ahead and define it with our var keyword, if we hit Control S to save, we can see that error going away. And now that we have our Whitespace turned on, we can see that there is inconsistency in our spacing or indentations, so we've used two here, two here, and then randomly right here we started using three spaces. So, since these are in the same scope here, we need to be consistent and you can see we have three, and it says Expected F at column 3, not colum 4, so columns being a column of characters. So if we have one right here, we have two, column two goes all the way down with the second character. Column three with the third character. You can see that one, two, three, these are three, and it expects our next line to be at that third column as well. So if we delete that extra space, hit Control S to save, we can see that error going away. Right here, going to see we are expected to have a space between if and our statement. So this is just another little standard here, we have a space between our if and then, our condition, and just like we saw here it expects a space there between our parentheses and our brackets as well. So if we hit Control S to save, we take care of both of those errors and we see our alert errors, let's go ahead and fix all of those at the same time. We can say window.alert for all of these and use it as a method, and we fix all of those undefined errors. And right here we see Expected window at column five, not column six, so if we click on this it'll take us right to that error, and you can see we just have an extra space so we can delete that, hit Control S to save, and then the last thing we have to fix are just these two trailing spaces, so we can just go ahead and delete those, hit Control S to save, and now we have this little happy green question mark, here, now that we've fixed all of our JSLint errors. And a lot of these things are quite nitpicky, such as our little trailing spaces here and there, but it'll help us catch really sloppy errors such as creating a global variable or using a variable before it was declared, like when we forgot to use the var keyword. So not only is it important to correct those big errors, but it's also a good idea to get in a good habit with being very careful with our spaces and our indentation and the consistency of our code as well. And JSLint is a really easy way for us to detect those errors using a built-in tool. And one last thing I wanted to talk about is Tabs versus spaces, which is a very big debate, and spaces are one of the more recommended ways of doing it versus Tabs, so meaning when we want to indent something we could use a Tab, so if I press Tab, you can see it adds four spaces, or we can manually use our keyboard to add those spaces instead. So rather than trying to argue one side over the other, really, the most important thing is to choose one and be consistent with it. So I like spaces, it generally tends to be one of the more recommended ones, and you could use either two or four as the recommended standard. I like two 'cause it's quicker to just to press the space bar twice rather than four times. So we're going to go ahead and stick with that. You an see right here I have my spaces set to two, and if you want to change yours to two, or if you'd rather have four, whatever you prefer, you could come up here to Debug, open the Preferences file, and right here where it says space units, you can change this from two to four, or four to two, or whatever it is you want to change, then you just want to hit Control S to save, and come back to where you were. So now that we've fixed all our errors, I'm going to hit Control S to save, and I know this is really nitpicky, but once again, it's really important to write code in a clean way, because it'll make it much more easy to read and write with your code. So now that we've taken a look at coding conventions and using JSLint in our tool, in our next lesson we're ready to dive into our project and revisit our game.
Revisiting Our Game
In this lesson we'll be revisiting our game from Volume Two, and seeing how it can change using objects in our code. Since the main theme of Volume Three has been learning how to use objects in our code, and the concept of object oriented programming, I want to take a look and see how our game might change using objects in our code. And rather than watch me write out the code line by line like we have in the last two volumes, since our code is starting to very much increase in complexity and length, I think it makes more sense to kind of take a look at our code and go through it line by line, rather than watching me type all of this out. So first let's go ahead and take a look at our game and how I changed it and then we can take a look at the code itself. So you can see we still have our beginning scenario, here, so we're alerting and kind of setting the stage. And then we're starting with a random scenario, so you can see we have a little beginning scenario here. So you press OK, and now it's going to ask us to name our character, so maybe we can name our character Bob. We can press OK, and then it's going to ask us to choose a class, which is pretty cool. You can see that the complexity of our game, here, is really starting to evolve and be more familiar in kind of a RPG type situation where you have the class, you have stats and you can choose different paths. So we have three different classes to choose from, we have soldier, doctor, or politician, and all of these are going to affect the outcome of our game, here, so let's say maybe we're going to be a politician, so I can say politician, press OK. And then it's going to alert our class, here, and our name, and our scenario, now, so it's much more personalized, here, as we're going through our story. Then we have our scenario, in which we encounter a zombie. So we have two actions we can take, now, we can attack or we can attempt to sneak by the zombie. So, depending on what class we chose, we might have different strengths that affect this outcome. So maybe I want to attack, and we can see the result here, we charged the zombie, we crushed our foe, press OK. Just kidding, (laughs) we're not strong 'cause we didn't choose the soldier class, so we're actually bitten by the zombie and we die, 'cause we failed our class check, which is happening here in our code. So rather than winning we spend eternity with the zombie, and that's the end of our game. And then we see the results, "you lose." So let's go ahead and take a look at the code and see how I got to this kind of result. So I'm going to go ahead and drag out the window, here, so we can see more of our code, and I'll go ahead and add comments in here and explain more in depth, and it'll be in our chapter, or lesson 10_end folder, so you'll be able to see the comments in that folder after we finish. But I've removed them for now so we can read through this easier without having to see all of those in there. So the first thing I've done is I've declared a variable which is going to store the outcome or whether we win or lose. And if we scroll to the end of our code, here, the very last thing here is it's going to check an outcome, it's going to see if the outcome is lose, or if the outcome is win, and then we see "you lose" or "you win" based on the outcome, which is determined elsewhere in our code, which we'll get to in just a couple minutes. So we've seen our scenarios here in our prior volumes, so this is nothing new here, we just have a list of very, of possible scenarios here. And it's going to alert a random scenario here to start with which we saw in our last lesson as well. We still have our random number function, so all of this is from last volume. If you want to remember how we wrote that, you can go back and watch that in Volume Two. So, the first new code here is starting here on line 26, where I created an object for the character. Since we're modeling real life things in our code, it makes perfect sense to have our character, and our character has certain properties that help describe our character as well. You'll notice I used an object literal instead of an object constructor, because we only have one main character, so it makes sense to use a literal, or, to instantiate our object at the same time we create it. So I've added a couple properties here to our character, we have health, we have strengths, and we also have stealth. And all of these are going to be used later down here in our code. Then we have a name, which is just a prompt, and it stores a response to this question as the name of our character. That way, anywhere else in our code where we want to refer to that name, we can just say character.name like you see down here. So the last thing inside of our character object is we just have a class which is storing the result to a response and it's asking us to choose from three different classes. We have the two lower case method here, that way we can type in any of these and it's going to convert it to all lower case so it works that way if someone types in "Soldier," like this, rather than "soldier" lower case, either one is going to work. Further down here, I also did a check, checks to see if someone typed in their name in our prompt, that way if someone tries to be funny, we can go ahead and see this, press OK, if we decide not to enter a name here, then after this check it's going to alert the user that they still need to enter their name. So if you choose not to enter a name, then it just gives you a random name. So moving on, so it's going to say if this doesn't exist, we can use this not operator, say, so if, no character name, if not character name, then go ahead and give another prompt asking them to enter their name again. Then once again, this is the second part we saw. If they still don't enter a name, then it's just going to assign them a random, kind of unfortunate name there. So after our name check here, just to see if no, the person, the player, doesn't enter a name, we have our three different classes. So we're saying if the character class is set to soldier, which is all based on the response to our prompt up here, so if soldier the character's going to get a bonus strength of five. If their character class is a politician their stealth, they're going to get a bonus to stealth of five, so we'll go from zero to five, or zero to five. Or, if they're a doctor, their health will go from five, they just get a little bonus to health, and their health is increased to seven. Then we have our first scenario, where you encounter the zombie, and you have the option to either attack or to sneak by the zombie, so it's taking this prompt and it's storing whatever you type in as a variable of choice. So now we're checking, we're saying if our choice, if whatever you entered here is equal to the String attack, then it's going to perform one more check and it's going to see if the strength is five. And if your strength is five, meaning if you're a soldier, then you're able to slay the zombie and loot the store. And then the outcome is win, and then it'll also outcome, it'll alert that you win. And then your character's strength increases as the result of this encounter. So since you have successfully beaten it, you've now gotten stronger, and your strength is increasing. Which, just a little note here, our increment operator, here, our ++s, when we use JSLint, it throws up a little error here. So we can see that we have two little ++s here, and we also have a little pesky space there, as well, so I can go ahead and delete that and fix that error. Woops. So it's going to throw up an error whenever we use that increment operator, because the author of JSLint, woops, we're getting another little Live Preview error since we're coming in here and messing around. But since the author doesn't care for this increment operator it's going to throw up an error, but it's a common convention so you can use the increment operator if you want. If you want to search that problem or research that problem, see why he doesn't like it, then you can just go ahead and search for this error in a search engine, and you can read all you ever cared to about the increment operator. So, moving on, it's going to check for our character strength, see if it's equal to five, otherwise if it's less than five, you're not going to be able to defeat the zombie using strength and your outcome is going to be to lose. Now, if you chose sneak instead of attack, so it's going to say if attack, run through all this, but if you chose sneak, or if you also chosen sneak by the zombie, that way there's a little flexibility in what the user's typing and you could say sneak, or sneaky by the zombie, then it's going to check your stealth, and if you successfully have stealth, so if you chose politician, you're going to be able to sneak by the zombie. Otherwise, if you chose doctor or warrior, soldier, then your stealth is going to be less than five and you're not going to be able to sneak by the zombie. But we have a little additional check, here, that says, if your stealth is less than five but your strength is five, so if you're a soldier, if you fail the stealth check you can still sneak by the zombie using your strength and crush him and then your outcome is equal to win. Otherwise, if you fail the stealth check and the strength check, then you just go ahead and lose. And then we have our final check of outcome equals lose, and outcome equals win. So you can see here just by using objects and properties of our object, how we've really made our game much more dynamic and much more interesting. And I know this is kind of a high-level overview of the code, here, but like I said, if you want to go here and play around I'll add comments here, and you can take a more in-depth look at this code. I've also gone ahead, here, if I shrink my window, and I've added our games from the previous volumes so you can compare them and see how our game has evolved throughout time. So we have volume1js and we have volume1.html, so if we double-click this and open that up in the browser, then we can see our game from Volume One. If you want to see the game from Volume Two, you can just go ahead and bring this up in the browser and do the same thing and compare the code, and see how we've changed and learned and evolved as we've gone throughout our volumes. So, now that we've taken a look at how our game could change by incorporating an object into our code, in our next lesson we're going to get our Volume Three assignment.
Volume 3 Assignment
In this lesson we'll get our Volume Three assignment. In our last lesson we took a look at our game and saw how we could use objects to increase the complexity of our game and to build on the interactivity between the player and the game itself. So for your Volume Three assignment, you can either build on the complexity of the existing game, as we saw in the last lesson, maybe by using the health property, which you may have noticed wasn't used in the outcome of the game. So go ahead and take advantage of that doctor character class that's built in there, and use the health property to change the outcome. Or, if you wrote your own code in Volume Two, and changed the game in your own way, go ahead and figure out how to use objects either to create your own character object to use, or you can use objects in any way you can think of to enhance the game. And, of course, if you didn't like zombies, and chose to create your own adventure game with a different theme like pirates or whatever else you can think of, go ahead and use objects to enhance the game in that way. As you go along just keep in mind that the scope of the code you're creating, and just think how the scope is changing depending on the code you're writing, and try to stick to a coding convention and maybe use JSLint to help you write clean and elegant code. So, good luck creating your zombie adventure game, or the game of your own choosing. And here our adventure together ends, but your JavaScript journey is really just starting. And now you're armed with all the tools you really need to have a solid understanding of the lexical structure of JavaScript or all of the core features and functionality the major, big puzzle pieces that we can use to create code of our own. So I hope you've enjoyed Quick Start to JavaScript, and especially from Volume Three, and I'll see you around next time.
Course author
Susan Simkins
Susan is a web design author for Pluralsight. Growing up, Susan was both a passionate artist as well as a computer tech aficionado. When she discovered the world of web development, she found that...
Course info
LevelBeginner
Rating
(703)
My rating
Duration1h 24m
Released17 Jan 2015
Share course