JavaScript: The Hard Parts, v3

Math Operators & User-Submitted Data

Will Sentance
Codesmith
JavaScript: The Hard Parts, v3

Lesson Description

The "Math Operators & User-Submitted Data" Lesson is part of the full, JavaScript: The Hard Parts, v3 course featured in this preview video. Here's what you'd learn in this lesson:

Will introduces JavaScript's type coercion, a design feature that automatically converts data types to make the language more flexible, especially when interacting with web browsers. Operators in JavaScript behave like functions but operate on values adjacent to them, and type coercion helps handle data from user input as strings, converting them to the appropriate types for operations. Understanding this helps write more bug-resistant code and effectively handle JavaScript's quirks.

Preview

Transcript from the "Math Operators & User-Submitted Data" Lesson

[00:00:00]
>> Will Sentance: We are now going to explore one of the most notorious parts of JavaScript, type coercion, but in doing so, we're actually going to get to wield an amazing feature of JavaScript, the symbol, to achieve some metaprogramming, which we're going to see is the ability to take control of some of the underlying features of our programming language. So here we go. Type coercion operators and metaprogramming, infamous.

[00:00:29]
I originally wrote notorious, but infamous, er hidden. But nevertheless incredibly powerful system built into JavaScript that is not a mistake, it is a design feature to be flexible to the fact that JavaScript doesn't run in isolation, it runs in a web browser. And we're going to see that that leads to data types that we might not expect that land in JavaScript, and that JavaScript's designers, especially in the early days, thought, hey.

[00:01:01]
Let's try and be helpful here and coerce them, change their nature to make them more usable immediately. Not something that's a mistake, but something that was by design. But to use it effectively depends on a deep understanding of primitives. We've heard a lot about, or we've pointed a lot, ha ha, pointed a lot about the distinction between maybe, data that's treated by value and that treated by reference, that is all primitives versus objects, or the stack versus the heap.

[00:01:30]
We're going to see that distinction clearly here. Operators, we saw earlier, very early on. How our higher order function, we might have wanted to pass in an operator as an argument into our function. We kind of wanted to say, hey, copy array and manipulate, pass in 123, and the operator plus, and the value 3, doesn't it? Seem unreasonable, we could have done that. We're going to see that operators and understanding how they're functioning is really important as well, and they're going to be considered action dispatchers, not functions.

[00:02:05]
They go off and kick off some work, maybe some mathematics, but often, believe it or not, some type coercion. And then we're going to understand memory under the hood. We're going to do Symbols that give us manual control over particular coercion pipeline, the to primitive pipeline. And even more metaprogramming, and if we can understand all this, we can write more bug resistant code and answer hopefully many of interviewers' favorite gotcha JavaScript questions, not from a learned by rote approach, but a learned by first principles approach.

[00:02:48]
So, here we go. We are going to be building a product page, and look at this. I can't believe we're back, but with some very challenging code here, we're going to be building a product page that we need some math for. We have some built-in math that's going to allow us in our product page to have a price of $7 or whatever, quantity of 3 items, and we're going to do some math on it. Are we really going to do this?

[00:03:14]
You bet we are. Here we go. Line one, Tenzin. You're our lucky person, we're back in our global memory, this time focused primarily not on our function calls, but on our operators here. What are we declaring first, Tenzin? We're declaring a constant price. Yep, sending it to the value of what? 7. Excellent. Especially given this is not too challenging here. Let's be as complete as possible. That sounded like a polite reprimand for a teacher.

[00:03:49]
Let's do our best here. I'm sorry, it's really good. Alright, next line, Tenzin, sorry, sure, then we said another 10 is better than every one. OK, alright, thank you, Tenzin. Next, yeah, go ahead, sorry. Quantity with value of 3. Beautiful. And then finally we declare total. Yep, and then we multiply price with quantity, right. So we've got to do some math, we might think, well, how do I do that, let's not, never take anything for granted in programming, right, like, maybe we don't know how to do that, maybe it's not possible, we do, we have built-in functionality, although not called functionality, that enables us to do math, and that is our operators.

[00:04:28]
Our operator here is that star one representing multiplication. But it doesn't behave a million miles away from a function, but notice how it's kind of flipped, you don't pass an input into a function call, instead you have an operator that acts on stuff either side of it, acts on stuff adjacent to it. But that's, don't lose sight that that is analogous to what a function's doing, but a function acts on stuff inside parent.

[00:04:56]
An operator acts on stuff outside of its position on the line of code. So in this case, our star, representing multiplication. Again, this is that, a bit like that thing, like, hey, if you really think about it, but it is worth sometimes doing that and realizing we are dispatching action, we are committing action here via the positioning of our operator, the thing that can do tasks, and the positioning of our operands.

[00:05:24]
The things on which that task is being done, in this case, price and quantity are operands and our operator is our star, and the dispatch action, do stuff like multiply them, exactly as we heard Tenzin say, we are going to evaluate the line price star quantity and price is 7, 3, and we know that this will evaluate to 21 and we store that in total. So we dispatched some action, which was go and do the multiplication, that's built into the language.

[00:06:00]
Great, but we want to let our user input this quantity. So we're going to create a webpage where the user can enter the quantity. Now in practice, people, we're here for JavaScript, we're not here for the DOM or the web page, that's in different hard parts. If you do want to go into that, explore UI hard parts. So for now, our quantity is not going to have a value. We're again, not too concerned about what it is initially, because we've used let here to enable us to change out its data, if we are being explicit about how from our webpage, so let's draw our webpage in here, I think it's worth drawing our webpage in here.

[00:06:49]
So here's our webpage, and we're going to have, you know, price of some amount, and then we're going to have the ability for the user to enter a quantity, and on submission, which we'll get to in a moment, they can then have that quantity enter JavaScript, but we're going to have that quantity typed in by the user now, and if we were to get into the weeds of how it's going to go from being in the DOM, which is where our view is handled in JavaScript, the thing the user sees, it's going to use our document and then the built-in method on it, getElementById and maybe we've given an ID for this particular form field of q and we're going to grab the value from it, and that's going to be thrown into JavaScript, but we're not here to get into the details of how we access those pieces, but to instead say, we are now having the user submit our quantity, let's say they submit 3, and now it's going to be passed into JavaScript.

[00:08:01]
When we do, things immediately get interesting. Whereas before our quantity was set by us to 3, now the user sets it. And they typed in 3. And I hope, and I assume that that will come into JavaScript as the number 3. Who thinks it comes in as the number 3? That would be sensible, right? No. Instead, it comes flying into JavaScript as the string 3. Yay! And so into quantity, I'm going to do it with single quotes, as long as I'm consistent, you know, I'm not going to be consistent, but as long as it, the first one's a single quote, the last one's a single, right, as long as it's the same quotes on each side, we're fine.

[00:08:42]
I never know cause it's easier to see that it's a string with two quotes, but meh, cause I sometimes use quotes for. Oh, I don't know. Yeah, whatever, now we know it's a string, there we go. Definitely, it's a string either way, but JavaScript gets a string from the web page. So, let's save our function. Tenzin, what's the function we're saving here? It's called onSubmit, and it's just a regular function, and people again, because we're not focused here on our actual interplay, interfacing between the web, between the DOM, that's the representation of the stuff that shows up on the webpage of the user, and the JavaScript land, they both run in the web browser, because we're not interested so much in the interface of those, if you are, as I say, go to UI hard parts, because we're actually interested in the type work that's going on in JavaScript land, I'm going to again simplify and have our onSubmit function when the user clicks submit.

[00:09:46]
That is going to trigger the onSubmit function running. Now in practice, again, if you're interested, that onSubmit function would be attached as a handler to a click event, such that when the user clicks submit, the onSubmit function is automatically run, and when we get to the async hard parts tomorrow, you might be able to join some of the dots on how that's working, which will be cool as well, it'll be nice to refer back to this.

[00:10:17]
But all we're going to do here is say that the user has clicked and our onSubmit function is executed, a new execution context, even this we're not too worried about, because we're here today to talk about data types, but into it we go, and we hit total is the result of, as before, price by quantity, price is 7, and quantity is the string 3, yay! Immediately, we have a wonderful built-in feature of JavaScript, that the string arrived, the number arrived as a string into JavaScript.

[00:11:01]
This boundary is going to be a problem. We're doing math on a string. That may look like, and I don't ever want to assume that we can't recognize when we see that is the number 3, right? Yeah, but it's no different to the letter A or the letter A3. It may have the 3 in it, but it's not a numeric value that can have math done on it, it is just the letter 3. And so this here, surely is an error. Right, that would be a very sensible language that would say you cannot multiply a number by a letter, that doesn't exist.

[00:11:42]
But do not panic. JavaScript's generous designers, and I give them credit. This was from day one, a language designed to interface between these two environments. The DOM, where when the user entered the number 3, it got thrown into JavaScript as the string 3. This was from day one designed to be a language that made that interfacing between the two less strenuous for developers. So what does the JavaScript engine do?

[00:12:17]
It introduces type coercion. As soon as it sees math operator, star, and one side be a number and the other not, a string, or we're going to see all these rules in full, but I don't want this to be about the rules so much as the general structures. As soon as it sees a string 3, it is going to hit both sides with a toNumber, I'm going to use that little symbol there, type coercion. It's going to convert our string 3 into the number 3, and our number 7 is already a number, and so we get automatically 7 multiplied by 3, no problem, and into our total, it goes.

[00:00:00]
A toNumber, my little symbol there for the toNumber, type coercion is kicked off, and now we have just a regular multiplication operator.

Learn Straight from the Experts Who Shape the Modern Web

  • 250+
    In-depth Courses
  • Industry Leading Experts
  • 24
    Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now