Check out a free preview of the full Introduction to JavaScript Programming course:
The "Challenge 1 Solution" Lesson is part of the full, Introduction to JavaScript Programming course featured in this preview video. Here's what you'd learn in this lesson:

Kyle walks through the solution to Challenge 1.

Get Free Access Now

Transcript from the "Challenge 1 Solution" Lesson

[00:00:00]
>> Kyle Simpson: One of the items stated that we wanted to set ourselves up a few variables. And I indicated that some of them should be constants. If you have the advantage of using ES6, which is, at the moment, going to require using a transpiler, it's a tool that converts your code, so it'll run in browsers.

[00:00:17] So, it's possible to do and a lot of people are doing it. I encourage it if you're writing JavaScript, but might be slightly overkill for what we're talking about. So, either a var here or a const, if you are using ES6, would have worked. If we put a var here instead of a const, the only difference is that we're not going to get an error if we were to accidentally change the variable.

[00:00:36] But, by convention, if you say var, and you have an uppercase variable like that, by convention, people know, don't ever assign to a thing. So, it's the difference between a convention that signals what you want, versus the language actually enforcing it. So, even without the enforcement, we can still get a long way.

[00:00:55] So you could have taken these as vars. Course my bank balance is something that you would typically think of as changing. Biggest reason why I make this a variable instead of a constant, it's a constant for the purposes of our program. That is that we don't change our bank balance.

[00:01:11] But the biggest reason why I'd make it a variable is because it might be the kind of thing that you'd want to prompt a user for. So, if you were gonna try the prompting, you were gonna do it. And it's an important note, by the way, that constants have to have an assignment.

[00:01:26] So you can't say something, like, if you're doing a real const, you can't say something like const foo, because it doesn't have an assignment and it could never be given an assignment. So that has to be an explicit thing that's getting assigned to it. All right, so here's my bank balance, that would be considered a variable.

[00:01:46] Now, my amount is gonna be kind of my running total, if you will, of how much I've spent. We'll come back to the functions in a minute. But the main meat of what I wanna do is, I wanna loop through, as I hinted in that description, I wanna loop through and keep doing something for as long as I'm able to do it.

[00:02:05] So basically, I'm figuring out what my purchase amount is, and I am being somewhat irresponsible. I'm just gonna keep spending until I don't have any more in my bank account, right? So here, I'm going to say while the amount is less than my bank balance, okay. So amount = amount + PHONE_PRICE, is buying a new phone.

[00:02:24] And you notice my usage of comments here. In this comment, I didn't say add the PHONE_PRICE to my current amount. 'Cause that would be repeating what the code already said. This was more a why, or a how, kind of an explanation. Or, sort of a meta explanation. So I'm indicating here that you're buying a new phone.

[00:02:44] Now, we want to know if we can afford the accessory. I indicated, in that problem statement, that you would want to be able to purchase an accessory, like an extra charger or whatever. You'd want to purchase the phone accessory for each phone, assuming that you haven't gone over a certain threshold of your spending limit.

[00:03:01] So we had a threshold that we declared as 200 dollars, and after that, we might buy phones, but we wouldn't buy any more accessories. Okay? So just a simple little expression in code of how we might be thinking about things in our mind. So as long as the running total amount is less than our spending threshold, we do want to add in the accessory price.

[00:03:23] Otherwise we would just keep going until the amount was not, until the amount went greater than the bank balance. Now, amount, we don't want to forget to pay the government, so we now say amount is equal to amount plus, and here I call a function, I say calculate tax.

[00:03:47] So, that's a set of things that I might do only once, or I might do multiple times. In this program, I'm only doing it once. But there's still value in putting it in a function, because this code is more understandable than if I dropped that same code directly in here.

[00:04:05] Because the name of the function explains something about what I'm doing. I'm taking adv of the fact that I can name this function something like calculateTax. Whereas, if I took just amount times 1.08, or whatever I did, that would look less reasonable, or it would make less sense.

[00:04:23] So another virtue of using functions is that you could put in a name for that section of code that makes the code more understandable. So, our calculateTax, we take in an amount, and we multiply it by the TAX_RATE. So, TAX_RATE being set up as 0.08. So this tax amount is just the tax, the $12 or $8, whatever it would end up being [COUGH].

[00:04:53] And we add that to our existing amount. And now, we then say, your purchase amounts, so this is like the cash register. Your purchase amount, and I call formatAmount. And the reason for that is, I want it to print out a nicely printed US dollar figure. So we have, we're going to put the dollar symbol in front of it.

[00:05:14] And then we want to call that two fixed method to round it to a certain number of decimal places. So I'm calling that format amount. And then, finally, as kind of an extra little flourish here, I would ask, did I go over my bank balance? And if I did, I'm going to print out, you can't afford this.

[00:05:34] Now, the way I've set up the program, of course I've gone over my bank balance, because I didn't stop until I already went over it, and then I had to add tax on. So, thankfully I am preventing myself from completely running my bank account down to zero. But that just illustrates some of these concepts that we talked about.

[00:05:51] You can see that there are conditionals to help us make a decision. Should we do something or not. In this case, the decision is whether or not we print something.
>> Kyle Simpson: Here, the conditional is whether or not we do something extra inside of this loop that's happening. Here, the conditional is deciding if it's time to stop the loop, or if we should keep going.

[00:06:12] These functions are things that we can call one or many times. They're a collection of things, we can pass values in as we are doing, we can pass arguments in that get set to these parameters. We can also take advantage of return values to return things out. You'll notice that these two functions don't make any changes to the variables outside of them.

[00:06:32] And that's actually an intentional design decision on my part. Rather than me saying in here, instead of saying return, I could have said something like amount equals amount plus the tax rate. Right, I could have done that. But if I'd done it that way, I'd be making what's called a side effect of a function call, which would work.

[00:06:51] We saw several examples of that earlier with the foo and bar functions, but it's typically considered to be a less graceful form of programming for your functions to have those side-effects. So you typically will think about a function as being entirely self-contained. You pass in a value, or multiple values if you need to.

[00:07:10] You get one return value out, and everything that happens inside of the function is sort of self-contained, and you don't make any changes outside. And you try not to rely upon stuff outside of the function as well. Although there are cases where it's inconvenient to pass in everything.

[00:07:25] So these are not hard and fast rules, but just stylistically, you typically wanna design your functions to have as little impact to the outside world as possible. There's one big caveat to that, which is not a topic that we're gonna go heavily into right now. But there's one caveat to that, and that's the caveat that closure is when you intentionally want for a function to remember stuff outside, so that it can keep track of its state.

[00:07:51] So there is a design style or a feature in JavaScript called closure, and we intentionally do that sort of stuff. And I covered that in basic detail in chapter two of the book, so you can go further from this class and read about a basic expression of how closure works in chapter 2.

[00:08:07] And I also have a full book about closure, the scope and closures book is really kind of all about that so there's plenty more to go. If you wanna learn more about how that works, we definitely won't worry too much about it. But there are places, just suffice it to say, there are places where you intentionally do decide to have a function rely on outside variables.

[00:08:26] Yeah let's see. The question is-
>> Speaker 2: 2 then just came in there at the bottom?
>> Kyle Simpson: Should a function always return a value, even if you don't have return in the function? Functions only return an explicit value if you actually say return. Normal functions, that is. If you call a function and then you do not have a return, it sort of implies that there is a return undefined at the end.

[00:08:52] But there is always a result from a function called, it's either that implied undefined, or whatever you explicitly return. And the question of should a function always return, there are many functions that I write that it doesn't make sense for them to have a return value. So, there's no should it have a return or not.

[00:09:13] It should have a return if that makes sense. In this case, it makes sense for both of my functions to compute something and return a value. Sometimes you just have a function doing something, that's a function that maybe has a side effect like it's calling something or whatever, so.

[00:09:26] There's plenty of places where return values don't make sense. Then, the next question was, in the program, the amount is always going to be greater than the bank account, so both the console logs will be printed. Why are we doing it? It's just a simple demo. I wanted to show you that [LAUGH] there's a way to decide whether we are looping.

[00:09:44] We could have been more nuanced about it and said, well, amount is less than bank balance minus threshold. Or something like, we could have said I want to spend until I've spent to where my threshold is under $100 left to my bank account. We could've done it that way, and then of course.

[00:10:03] But the point here was just to illustrate the different ways that conditionals can be woven together in our program.
>> Kyle Simpson: The next question, why are you returning amount.tofixed if you may purchase more than 1K or 100, I guess he meant, how the amount will be printed. So it's important to understand tofixed two, that indicates decimal places, not digits in your number.

[00:10:35] So this only means that I wanna round and pad my decimals to two decimal places. The amount on the left hand side, if I'd gone all the way up to five thousand dollars, or five million dollars, or whatever, we can have as many digits on the left hand side.

[00:10:49] There's another method called toprecision, if you want to actually restrict the number of digits that show up in a number. For those of you that had science classes, you'll know about the difference between precision and not. So there's a toprecision method that can be used for that purpose.

[00:11:05] But here tofixed is only dealing with the number of decimal places that we get out.