DEV Community

Daniel John Keefer
Daniel John Keefer

Posted on

Type Coercion in Javascript

Kid in Transformer costume gif

Type coercion is Javascript is the automatic change that happens to a value based on the context of the code around it. For example if you were to declare some variables like:

let someNum = 4;
let stringNum = "7";
let aString = "sixteen";

and you wanted to perform some functions or manipulations with those variables, you could concatenate stringNum with aString that pretty straightforward.

stringNum + aString; // output: '7sixteen'

But what if we add stringNum with someNum ? One is a string the other is a integer! what will happen? Type Coercion, thats what happens. Javascript see a single character string that is also a digit and assumes it is far more likely that you want to sum the two numbers together. Similarly if we were to try and concatenate aString with someNum javascript sees a long string and assumes that rather than adding the sum of the ascii character codes to the number four you want make the number a string and concatenates it.

stringNum + someNum; // output: 11
aString + someNum; // output: 'sixteen4'

While this can cause some funky errors if you aren't careful it also allows for some pretty elegant code in the form of short circuit logic. The values null, undefined, false, '' and 0 are falsey in javascript and all other values are truthy. meaning that when javascript functions are expecting a boolean those variables a type coerced to either true or false based on their truthiness. Here are some examples:

("" || "some populated string."); // evals to true
(0 || null); //evals to false
(1 && undefined); //evals to false

We can use this truthy and falsey properties of the type coercion in javascript to our advantage to write some elegant code as well in what's called short circuit logic. For example, say we have a website that blogs on a topic. And that providing your email is optional during the sign up process. But to everyone that has given their email, we will send a newsletter. An example user might look like:

{
  "users": {
    "user_id_string_a": {
      "name": "Stephen Strange",
      "email": null
    },
    "user_id_string_b": {
      "name": "Tony Stark",
      "email": "tony@starkindustries.com"
    }
  }
}

We can see that ol' Steve has not provided his email but tony has. is there some way we can use type coercion to write a piece of code that sends the newsletter to the users with emails but skip the ones with no email? Well yeah, but you probably saw that coming. We could write something like:

function SendAllMail(users){
  for(user in users){
    user.email && sendNewsletter(user.email)
  }
}

// the function 'sendNewsletter' in 
// this example would just take in 
// an email address and then as an 
// output send a newsletter to that 
// address

So how does it work? when the function get to each user in turn with in the for loop it uses the the user.email property as the first half of an boolean comparison. In Dr. Strange's case the code collects the null value and then knowing it has to do a boolean comparison, type coerces it to false as null is a falsey value.

The code then 'short circuits' knowing that the first half of the and operand is false causes it to immediately evaluate to false skipping the code written in the second half.

Conversely on Tony's turn through the function, user.email is a populated string, which is truthy. When it gets type coerced, it becomes true which forces the code to look at the other half of the && comparison. this then executes the sendNewsletter(user.email) function, ensuring Mr. Stark remains abreast of all your latest news.

So that's it, thanks for the read and I hope you can use your new understanding to write more awesome code then you could have before. And if you know more than me and I've messed up in my explanation, please comment and help me write more awesome code then I could have before <3. --xxKeefer

Top comments (0)