Lesson Description
The "Math Operator Type Coercion" 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 explores type coercion with math operators, showing how strings are automatically converted to numbers for multiplication and related operators. A side effect is that addition with a string operand triggers string concatenation instead of numeric addition. To avoid unpredictable results, manual type coercion using the unary plus operator or the Number() function is recommended to ensure consistent numeric operations.
Transcript from the "Math Operator Type Coercion" Lesson
[00:00:00]
>> Will Sentance: What about some other math operators? Do they coerce a number? Let's see. Well, let's set some max quantity. Did I keep saying quality? Oh no, I kept saying quality, didn't I? Quantity. I did think it was strange, I was saying, okay, there you go, quantity, that was easy to change, and max quantity limit. Tenzin, what have I added, my, so my DOM gives us the number, uh, the string 3, and again we're being a little bit kind of in terms of our ordering of code, a bit more relaxed, because here we're interested in how the type behavior, the data type behavior is working, less about the journey of the execution, it doesn't have any profound consequences here.
[00:00:41]
So let's just adjust this existing code to evaluate what happens when we set a max quantity limit using our relational operator here, the little caret, which says if the left side is less than the right side, then evaluate to true, so we can do some task accordingly. So you can see a conditional here, but first, let's add our max quantity into global memory. Help me out with that. Tenzin, I know we've already done this, but help me out with our max quantity in global.
[00:01:19]
Yeah, we just set a max variable and set it to the value of 10. Beautiful, there it is, perfect. Our total is back to being undefined here because I'm adjusting my code as we go. When we call on submit, which we're going to do down here, we are now doing a bit more work inside of it, so let's just open up this execution context to have a little bit more space, and again you can see we've gone from being very concerned about the exact flow of our code to being a little bit more relaxed, it doesn't have significance for what we're doing.
[00:01:55]
So into the on submit call we go, at the moment that the user presses submit, and we're going to do two things inside. We're going to first produce our total, and then we're going to secondly do a conditional check and, whew, who knows what's going to happen. Tenzin walk me through, firstly, the coercion done with our multiplication operator, to is going to be the result of, or to walk me through.
[00:02:24]
Sure, it sees that quantity as a string. Yeah, which is a string of 3, yep. And it automatically fires the toNumber. Yep, beautiful, automatically fires the toNumber, as the multiplication, yeah. It turns it into 21. Yeah, which is all our favorite meme number. If any of you remember that, no, probably not. Alright, and then we hit the conditional, where we have another operator and operands business going on, and this one says to do what Tenzin?
[00:02:58]
Checks for the condition and evaluates if quantity is less than max. Yeah. And those values turn out to be false because quantity is, well, let's see, so quantity, max is what value? Quantity is 3, or quantity is 3 and max is 10. Max is 10 and quantity is what? String of 3. Well, is a string of 3 less than 10? I don't know what that means, don't panic. We have another operator that kicks off our toNumber.
[00:03:33]
And so our 10, well, that's the same, and our string of 3 coerces to the number 3. And so there we have, is 3 less than 10. It certainly is, and we go all good. So, our relational operators to people, also kick off the toNumber coercion. Let's hope that all math, including addition, also kicks off toNumber coercion. I assume it does. What a strange language that would have some math operators kicking off toNumber and some something else.
[00:04:09]
Let's use the addition operator to add a donation. Let's expand our user experience and have them have the ability to add a donation. There it is, a donation that will say they're going to donate 10 bucks, whatever, and we know good old JavaScript's going to pass into our web browser, and we'll get a chance to do this in a moment, people, on all this, but I just want to build this out. The string 10, and so up here in our memory, we now have donation as the string 10, and we have our total as yet undefined, and now on submit, we're going to keep it a bit simpler again now, you can see I'm just kind of adjusting the code as we go a bit here, just to make it technically it needs to be inside of a function, because I really can't imply that the code runs purely synchronously, this is a function that is being called at the moment of the button submit being pressed, kicks off the on submit function being run.
[00:05:23]
I know it looks like it's being run just down the page, but that on submit function is being run when the user clicks submit. But yeah, just so that we know that the data is in there, or we hope it is, we'll see if it's checking that in a moment. And into our on submit function we go, where we hit our price multiplied by our quantity, plus our donation. I cannot see anything going wrong. So, our price is what, Tenzin?
[00:05:56]
7. Our quantity is what? The string of 3. String of 3, and our donation is what? String of 10, string of 10. So I can only assume that we're going to get a very sensible donation. The very sensible total, sorry, of this by multiplying our price per our quantity and adding our donation. So, let's kick off, so firstly, we do some of our what we call in the UK BODMAS, brackets over division, multiplication, addition.
[00:06:26]
What do you call it in America? PEMDAS parentheses, right, because we call them brackets, okay, that would immediately make sense. Excellent, so we start with our multiplication. 7 by string 3, we kick off type coercion and we get 7 by 3. Beautiful, 21. Then we have 21 plus string 10. I can only imagine we kick off type coercion again. Who thinks we kick off toNumber coercion again? We don't, exactly.
[00:06:59]
Instead, we kick off a different type of coercion to string. God, you've got to love a language that has such flexibility. And indeed we kick off toString, I don't quite, I'm going to do my toString coercion as this cute little quotes here, and so our string 10 is already a string, but our 21 is right now a number. How strange, it definitely should become a string. And so there we go, and when we add two strings together, which we call string concatenation, what do we get?
[00:07:41]
We get a longer string. This is a fairly mortifying result, to be fair, and notorious and, you know, gives any programming language a bad name that does this, but know that this, and I actually am not sure it's fully justifiable as a design feature. But I will acknowledge that type coercion as a whole is a justifiable thing because of this boundary. That's where this comes from. But, in this case, if either side of the plus is in fact a string, JavaScript automatically kicks off string coercion.
[00:08:24]
So we have toNumber, and we have now a coercion flow called toString. And when one is kicked off, it's going to depend conditionally on what data is at that moment in that operand's position. That is really underspecified. Right, if you think about a function, I want to, at the very least, I could write specifications. If it comes in as undefined, do something. If it does this, do something else.
[00:08:46]
TypeScript allows me to explicitly state in a syntactic form, as opposed to in logic form, what I can expect from a function as its output and what I can expect to, or what it can accept as its input. Here, I'm getting no control over that specification of what my operator will do. In the given moment, I mean I get to technically know that it will do certain behaviors, but, given my data flow could change, I'm in a very unpredictable space.
[00:09:28]
So most math operators, minus multiplication, divide, modulo, the one that checks the remainder on a division, there you go, exponential, exponent, the one that says raise to a power of, always toNumber, plus only does the legit math if both sides are already numbers. Flipping heck. What can we do at this DOM boundary, taking stuff that could be a string, maybe we've already inserted and said it's a number, maybe our colleague already, well.
[00:09:59]
What can we do to make it predictable? We're going to need to take manual control of our type coercion. We're going to need to set that our data is of the data type by manually kicking off our coercion steps. In this case, if we want to guarantee we're working with numbers, there's two primary options we can use, one being the unary operator. Here, it's putting that plus sign in front of our price, our quantity and our donation, we know our price is a number here, but, you know, we want to be careful, or it's actually calling the number built-in function that will manually kick off the toNumber coercion step.
[00:10:40]
If you want to guarantee strings, then we can use our string literal template, wrap the value in the string literal, which is our dollar sign, curly braces, back ticks, that will kick off our toString coercion manually, or we can call our string function to kick it off manually. Okay, so let's do that here, let's put our, we'll do it in blue. Let's put our plus in front. And now, before we use our math operators and or not math operators or behaving as such, to automate our coercion, we are going to manually hit each value with that type coercion.
[00:11:32]
Plus, no change, plus straight to 3, plus straight to the number 10, and now we, well maybe I can just cross these out. Now we have the number 10 here, we've already evaluated this. We have, therefore, at this point 7 by 3, the number is 21, 10 is now the number 10, we've crossed out our, probably the least effective way of showing that, we've crossed out our quotes, 10 is evaluated to the number 10, and now we're in the safe hands of doing regular math, not depending on our operator to simultaneously do math and preemptively run an action.
[00:00:00]
That is a type coercion, but instead to only do 7 by 3, the math, 21, and plus 10, the math 31. So rather than assigning in total, the string 2110, we are instead going to assign the value, the number 31. Okay, there's probably no other coercion, right?
Learn Straight from the Experts Who Shape the Modern Web
- 250+In-depth Courses
- Industry Leading Experts
- 24Learning Paths
- Live Interactive Workshops