Shirmung Bielefeld: == ? === ??? ...#@^%

Ping us if you have a link to the slides. Transcript
Shirmung Bielefeld

What is type coercion? When can it be useful? What happens when we choose to use == over ===?

JavaScript is a polarizing language, said to be full of “good parts” and “bad parts”. JavaScript’s type coercion is often bemoaned—one of the common “gotchas” for newcomers to the language. In this talk, we’ll unravel the complexity of type coercion and define a set of simple rules to make our lives easier. No more #@^%’s.

Video Video Video

Transcript

Thank you, I'm a software develop per at bark box in New York City where we develop apps to keep dogs happy and healthy. This is a picture of my dog, SmallTalk and me, this is a picture of a picture of me eating noodles, and this is a picture of SmallTalk eating noodles, now that you know all about me, let's talk about type coercion in JavaScript I've been programming predominantly with JavaScript for the past couple of years and I've gotten pretty familiar with many of it's quirks, one of it's quirks being type coercion, I hope to provide a better understanding how JavaScript converts between types and the various situations in which it performs type coercion. Butt let's back up, let's talk about type conversion in general. Wikipedia says that type conversion, otherwise known as typecasting or type coercion, is implicitly or explicitly changing an entity of one data type into another. So, what does that mean more simply? That's taking a type for example an Int and converting it the another type, a string. So, how does JavaScript handle type conversion? JavaScript is dynamically typed, as many of you know, which means that variable types are determined during script execution at Runtime. So, here, type conversion can happen in two ways. They can be explicitly specified by the developer in the code, like for example, directly calling Parsint which converts a string to an integer or to string or implicitly performed with type JavaScript. This type of conversion is typically referred to as type coercion, and type coercion is what we're focusing on today. So, why do I have to learn this? Honestly, it's very much built into the language. It kind of comes with the territory of JavaScript being die familiarically type language. The example type coercion is happening even with something as simple as a basic "if" statement. In this example here we know that if successful value.length will return an integer that would be the length of the value. However, the if statement here is expecting a pool Leon condition integer is not a Boolean. It converts it into a Boolean in order to evaluate this expression. Type expression can also offer more flexibility and can be convenient at times like when you're dealing with user input. And finally, get to know your language better, it's always important to understand what's happening underneath the hood. So let's build some foundational knowledge. Let's talk about converting types. There are two categories of types in JavaScript, you have the simple types, which are numbers, strings, Boolean, the values true and false Nul will and undefined everything else is an October, arrays, functions, regular expressions and of course objects. In the next three slides I'm going to try to define JavaScript typically implicitly converts between different types and use this knowledge for the remainder of the talk. So how does JavaScript convert from simple types to numbers, for strings there's an attempt to parse the string to a number, otherwise it returns an NaN or not a number. Boolean is converted to one, false is cob verdicted to positive zero.  ‑‑ converted to positive zero. Nu is converted to positive zero and undefined is converted to not a number. What about converting simple types to Boolean, numbers are converted to true unless the value is positive zero, negative zero or not a number these are converted to false, and strings converted to true unless the value is the empty string which is converted to false, Nul and undefined are both converted to false. And and finally what about objects, how are objects converted. When converting objects to numbers and strineses JavaScript will try to convert the objects ‑‑ by implicitly calling value of on the object. Or if value of isn't defined or didn't return a primitive type when called it will try to call two string on the object inside. Converting objects to Booleans is a bit simpler, they're converted to true. So let's take these guidelines and apply them to a few situations and let's start with conditional statements first. But let's quickly just make sure we're all on the same page about truth and falsey values in JTPA. Some examples of values that translate to true is 123, the string "smallTalk" the Boolean true, and objects. Some examples of values that evaluate to false in JTPA are the integer 0, not a number, the empty string, the Boolean fault, null and of course undefined. The conditional statements if for wile and do while aliening to valuablee valuable conditions, if it does not return a Boolean openerands are implicitly converted to ball listens, if example in this example Var equals document.get element by ID SmallTalk, it looks for an element with a particular ID in a DOM. Wit return an object if it finds an element or it will return null, if an object is returned the if statement will implicitly return it to true, null will return if implicitly converted to false. So switch statements are a bit special here, similar to an if statement the expected valuable Boolean condition, unlike the if, when evaluating the switch cases statements no type coercion is performed, so, in the previous if statement, values coerce to true or false depending on whether or not get element by I D returns an object or not. Here value will not be coerce true or false it will be treated as it's original type, because of that it will never satisfy case statement true since neither object nor null are equal to the Boolean true and it will instead enter the default case. Logical operators, which are of course, and, and or. Let the conditional operators convert to Booleans depending on the context, unlike conditional operators the operator is returned not the Boolean value. So incidentally this can be great for setting default values. In this example, Var value is equal to zero or apple, value is ‑‑ sorry the or operator is looking from left to right for the first true open aerator to undere return, it's converted to false, apple is converted to true and some value is set to the string apple. T omohiro Matsuyamacal operators, which are, of course, the addition and subtraction sign, multiplication and division sign and of course the module operator. Opener ands are converted to numbers, except for dates, which for some reason are converted to string, Var values equal the true plus null plus 5, true is converted to one, null converted to zero and one + the zero + five is six, value set to six: The interesting operator the take a look at here is the addition sign. The addition sign is overload in the JavaScript, so that means not only can it do addition between two numbers it can do string Concotenati no, when one is a string and the other opener and isn't, the other opener and is converted to a string. In this first clam example Var example is converted to the string maul talk + 2, the value set to SmallTalk + 2 is converted to a string 2 and then Concatenated this is happening left to run, 1 + 2 is add together because JavaScript isn't aware of the string that follows, then 1 + 2 equal to 3 is Concatenated to 3 small talk. Relational operator time. Those are greater than,less than, greater than equal to, or less than and equal to. Similar to the mathematical operator, opener ands are converted to numberser here even dates are converted to numbers an exception is strings are compared via lex graphical string comparison. Compared sequentially, similar to how you oridance e words in a dictionary. Keep in mind here any comparison involving not a number will evaluate to false. In this example, Var values equal to false, less than the string 1, 2, 3, false is converted to 0, the string 1, 2, 3 is converted to 123, and value set to true. Because, of course, 0 is less than 123. Now for the more Meaty stuff, equality operator. Equality means in JTPA ‑‑ values are considered equal if they are identical Boolean values, true is equal to true, note call to false, if they're identical strings, the string ABC is equal to string ABC but not to say ABCD. There are also considered equal if they're numerically equivalent numbers 1 is equal to is 1, positive 0 is equal to negative 0 in this case. Values are considered equal if they're the same object. And, again, not-a-number is special here, it's not equal to anything, including itself. And as you all probably know there are two sets of equality open pert or in JavaScript ‑‑ the double equal op perai to and triple. Dot double equal operator ‑‑ if it determines that the types are different. The double equals operator follows what's known as the abstracts equality comparison algorithm, a series of 22 steps used to determine the quality. When the expression meets one of the step conditions, JavaScript will return true or false accordingly, otherwise if it reaches the end of the series, it will return false. We'll get into a bit more detail about how type coercions are performed here, but first let's walk through an example. So, Var value is equal to null greater than or equal to zero. Using the knowledge that we obtained about relational operators this seems pretty straightforward, the relational operator implicitly converts to numbers, so null will be converted to zero, and, of course, steer row is greater than or equal to zero, so values set to true. But let's look at another example, offed Var value is equal to null, bobble call zero. This returns false. What the hell?! How does that make sense? Everything we've learned so far implies that null will be converted to zero here. But in short null is treating ad in a special way by a double equals operator, it only corresponds to undefined. There is only one of the many strange cases that involve the double equal operator. All due to and can be explained by following the abstract equality algorithm. So, the abstract quality algorithm is defined really quite clearly in the if ‑‑ language specification, I don't want to bore you with all 22 steps, by I did want to walk through what happens after JavaScript has determined that the two types are different and attempts to type course, which are incidentally steps 14‑22 in the algorithm. Null equals undefined and if one opener and is a string and the other opener and is a number the string will be implicitly converted to a number. If one of the opener and s is a Boolean, the Boolean will be implicitly converted to a number, if one of the operands the string or the number and the other operand is an object, the object will implicitly convert to a primitive. So the triple equals open aerator behaves similar to to the double equals open aerator except no type coercion is done, it uses straight equality comparison algorithm, nearly identical to the first thirteen steps comparison algorithm. But leaves out all the bits related type coercion, types must be the same initially in order to be considered equal. Otherwise the triple equals operator returns false. Since there are no unexpected type coercions being done, when using the triple equals operator ‑‑ equals results and it can be mump safer. So the tool I cam across preparing for my talk was this JavaScript equality table. A graphically displays the results of comparisons using the double qualms and triple equals operator, so green means expression of evaluator to true, white means expression evaluator false. Of so ininclusion ‑‑ as amentioned earlier it can be dangerous to use the double equal operator if you're not sure what you're doing, try to perform explicit type conversion when you're able to do so, so that was from my earlier slide, calls parse in or two string. And use the JavaScript console and ECMA script language resources this was provide foundational knowledge, but it's of course missing detail, the ECMA script language goes into this in depth. It's not too terrible love a read, surprisingly. Thanks, guys, come chat with me later if you'd like the discuss any of this or tell me about your dogs (Applause) ask cool, so we're early, you guys get the jump on the lunch queue. So ... head on out, you can thank her for having a zero lunch queue. Edit transcript via pull request.