{"id":11758,"date":"2022-07-28T15:56:35","date_gmt":"2022-07-28T15:56:35","guid":{"rendered":"https:\/\/www.htmlgoodies.com\/?p=11758"},"modified":"2022-08-01T16:25:02","modified_gmt":"2022-08-01T16:25:02","slug":"javascript-type-coercion","status":"publish","type":"post","link":"https:\/\/www.htmlgoodies.com\/javascript\/javascript-type-coercion\/","title":{"rendered":"Understanding Primitive Type Coercion in JavaScript"},"content":{"rendered":"
<\/p>\n
All programming languages, including JavaScript (JS), have built-in data types; these include strings<\/em>, numbers<\/em>, Dates<\/em>, Arrays<\/em>, and so forth. What makes JS special is that it is loosely typed. Hence, variables are declared without a type, which allows them to be re-assigned values of a different type at any time. This feature makes the language more dynamic, but also leads to more bugs than probably all other features combined! It is such a problem, in fact, that TypeScript<\/a> was created to bring strong typing to the JavaScript language.<\/p>\n Not that JS’s automatic type coercion is all bad – it is part of what makes JavaScript one of the easiest programming languages for beginners to learn, and undoubtedly played a substantial role in JS’s longevity and popularity. For more experienced developers, the path to less frustration is to take some time to learn the ECMAScript Language Specification Standard and become more adept at navigating type coercion’s many quirks. Consider this web development tutorial as a starting point on that journey, as we cover how JavaScript converts one type into another based on how variables interacts with each other in code.<\/p>\n You can learn more about ECMAScript in our tutorial: Asynchronous Programming in ECMAScript<\/a>.<\/p>\n Before we can talk about type coercion, we should establish what JavaScript’s types are, since you will not see them when you declare variables. JavaScript has seven primitive types:<\/p>\n What all of the above types have in common is that thy are not objects, and, as such, have no methods or properties, unlike say Arrays<\/em> or Dates<\/em>.<\/p>\n You may also want to check out our guide to Working with CSS Variables<\/a>.<\/p>\n Web developers can get a variable’s type (at that moment in time), using the typeof<\/i><\/strong> operator:<\/p>\n Number <\/em>and BigInt<\/em> have a related value NaN<\/i>. Short for “Not a Number”, NaN<\/em> is typically encountered when the result of an arithmetic operation cannot be expressed as a number. It is also the only value in JavaScript that is not equal to itself!<\/p>\n Amazingly, all type coercion issues in JavaScript are caused by the string<\/em>, number<\/em>, and boolean<\/em> primitive types (there is no way in JavaScript to coerce a primitive type to object or function)! Implicit type coercion happens when we mix different types within the same operation or series of operations.<\/p>\n The weird thing about booleans<\/em> is that all primitive values also have an inherent boolean<\/em> value, which makes them either “truthy” or “falsy”. Some of the rules that determine how non-boolean<\/em> values are coerced into true<\/i> or false<\/i> values are not intuitive, so it is worth going over those now.<\/p>\n The following values are always falsy<\/em>:<\/p>\n Everything else is truthy<\/em>. That includes:<\/p>\n That is why programmers can test for truthiness in an if<\/em> statement:<\/p>\n As long as the widget variable contains a non-empty string, the if<\/em> block will get executed.<\/p>\n Rather than let JS coerce expressions into a boolean<\/em> result, it is perfectly acceptable to do it yourself using the Boolean()<\/strong> function:<\/p>\n If you try to compare a variable of a different type to a number, JS will helpfully coerce it to a number, in order to perform an apple to apple comparison. When a type can not be coerced to a number, the returned result is NaN<\/em>. For example, an empty string will be converted to a zero (0<\/em>). Some developers have been critical of this behavior because they do not agree that an empty string should be considered to be a valid number, some have even gone so far as to state that “empty strings becoming 0 is the root of all coercion evil” (Kyle Simpson, the creator of the You Don’t Know JS<\/a> book series).<\/p>\n Not that implicit type coercion is all bad. It does allow us to do fancy stuff like this:<\/p>\n Just to be safe, you could make sure that index<\/i> contains a valid number by using the Number()<\/strong> function:<\/p>\nWhat Are JavaScript’s Primitive Types?<\/h2>\n
\n
How to Verify a Variable’s Type in JavaScript<\/h3>\n
console.log(typeof 42);\r\n\/\/ expected output: \"number\"\r\n\r\nconsole.log(typeof 'blubber');\r\n\/\/ expected output: \"string\"\r\n\r\nconsole.log(typeof true);\r\n\/\/ expected output: \"boolean\"\r\n\r\nconsole.log(typeof undeclaredVariable);\r\n\/\/ expected output: \"undefined\"\r\n<\/pre>\n
\/\/ outputs NaN\r\nconsole.log(parseInt(\"blabla\")
Implicit vs. Explicit Coercion in JavaScript<\/h2>\n
Coercing to Boolean in JavaScript<\/h3>\n
\n
\n
var widget = 'bolt';\r\n\r\n\/\/later in the code\r\nif (widget) {\r\n \/\/ do something\r\n}\r\n<\/pre>\n
var widget = 'bolt';\r\nvar isSoldOut = false;\r\n\r\n\/\/later in the code\r\nif (widget !== '' && !Boolean(isSoldOut)) {\r\n \/\/ do something\r\n}\r\n<\/pre>\n
Numeric Coercion in JavaScript<\/h2>\n
\/\/ Adds 1 to the currentIndex if the userId is 99.\r\nvar index = currentIndex + (userId == 99);\r\nvar info = userData[index];\r\n<\/pre>\n
\/\/ Adds 1 to the currentIndex if the userId is 99.\r\nvar index = currentIndex + (userId == 99);\r\nif ( !isNaN(Number(index)) ) {\r\n var info = userData[index];\r\n}\r\n<\/pre>\n