Coercion in Javascript

Coercion is a very important part of JS structure. Type coercion means that when the operands of an operator are different types, one of them will be converted to an “equivalent” value of the other operand’s type. Coercion has both good and bad side. 

The typeof operator return only six types:

  1. undefined
  2. string
  3. number
  4. boolean
  5. object
  6. function

NaN is more appropriate to ‘invalid number’. It is the only value that is not equal to itself.

Falsy & Truthy: The following are coerced to false:

  1. 0, +0, -0
  2. null
  3. NaN
  4. false
  5. undefined
  6. “”

All other values which are not in the list are truthy. An empty array is truthy.

+bar : variable bar is coerced to number value.

!!bar : variable bar is coerced to boolean.

~bar: equals to -(bar+1). Add 1 to bar and then negate.

// ~ operator's best usage:

var a = 'sajib';

if( ~a.indexOf('a')){
	console.log( 'Found it' );
}else{
	console.log( 'Not found it' );
}

“-” operator is only applicable for numbers. So, when we use string or other types in one or both side of the “-” operator, those values will be coerced to number. Whereas the “+” operator both applies for string and numbers. If “+” operator finds numbers in both side, it does addition operation and if it finds string on one or both side, it does concatenation operation.

// coercion to number from string	
var num = '123';
var bar = num - 0; 
console.log( bar );				// 123
console.log( typeof bar );		// number

// coercion to string from number
var num = 456;
var bar = num + ""; 
console.log( bar );				// 456
console.log( typeof bar );		// string

We shouldn’t compare two values with ‘==’ where one side is true. It creates confusing coercion.

Leave a Reply

Your email address will not be published. Required fields are marked *