codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Equality and Type Coercion in JavaScript

--

“I should’ve used strict equality comparison.”

Type coercion is when JavaScript converts values at its own discretion. At first it can seem like the Wild Wild West. Trust the computer? I don’t think so! Like any tool though, once you can harness its power you can do some pretty cool stuff. Let’s take a look at some comparisons with == and ===.

5 == 5
true
‘5’ == 5
true

How can that be? What’s JavaScript actually doing to convert string 5 to integer 5. Or is it the other way around?

What about these?

console.log(“3” + 1)
‘31’
console.log(“3” — 1)
2

In the first instance, 1 is converted to a string. In the second instance “3” is converted to an integer. Addition and subtraction are just another tool in JavaScript, so let’s see what MDN has to say about them! According to MDN, + is for addition and string concatenation. While -, *, these subtract or multiply operands. + has dual purposes, and JavaScript will use it accordingly!

One interesting case of type coercion is for null values. 0, undefined, null, and empty string count as false in JavaScript. Let’s take a look at these.

0 === false
false
0 == false
true

With the == operator, 0 converts to false, so they are the same. This would be helpful in looking for a value in an array. Let’s say we have an array of three hosts.

var hosts = ['Dolores', 'Teddy', 'Hector']

What if I wanted to check if there was a host in position 3? Right now, hosts[3] is undefined. However, I could use == and have null convert to undefined.

hosts[3] == null
true
hosts[3] === null
false
hosts[3] == undefined
true
hosts[3] === undefined
true

While to be safe, I would usually stick with === operator and check for the same type, it’s interesting to know what JavaScript does under the hood!

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

No responses yet