Type Casting in JavaScript

Type Casting in JavaScript

Introduction

Type casting is the conversion of a type of data from one type to another. In javascript, converting a datatype is a bit weird but exciting in how they behave in different conditions. One can do typecasting in two different ways:

  1. Explicit (or Type Conversion)
  2. Implicit (or Type Coercion)

Explicit Type Casting

When a user or a developer does the task of converting the type of data, then it is said to be Explicit Type Casting. The output result of any typecasting will always be so the type can be only converted to a number, string, or boolean.

  • To String :
var a = String(123); 
console.log(a, typeof a);  // "123" string
// Type of null is an object and it will be converted to string
var a = null;
console.log(a, typeof a);  // null object
a = String(a); 
console.log(a, typeof a);  // "null" string
var a = undefined;
console.log(a, typeof a);  // undefined undefined
a = String(a); 
console.log(a, typeof a);  // "undefined" string
// Boolean to String
var a = String(true); 
console.log(a, typeof a);  // "true" string
var a = String(false); 
console.log(a, typeof a);  // "false" string
  • To Number :
console.log(Number(null));  // 0
console.log(Number(undefined));  // NaN
console.log(Number(true));  // 1
console.log(Number(false));  // 0
console.log(Number(" 12 "));  // 12
console.log(Number("-12.34"));  // -12.34
console.log(Number("\n"));  // 0
console.log(Number(" 12s "));  // NaN
console.log(Number(123));  // 123

Note: By parseInt, we can also convert a string to a number. parseInt parses a string value and returns an Integer type value.

console.log(parseInt("10"));  // 10
console.log(parseInt("12s"));  // 12

It returns whatever is the first Integer value whereas using the number we got NaN.

  • To Boolean : Before converting any type of data we need to know about the term truthy and falsy. Truthy are those which will return a boolean value of true. Falsy are those values that will be returning a boolean value of false. Following are some falsy values other than them all the other values are truthy:
    • 0
    • Empty strings
    • null
    • undefined
    • NaN
    • false

Below, are the examples:

console.log(Boolean('')); // false
console.log(Boolean(0)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(null)); // false
console.log(Boolean(NaN)); // false
console.log(Boolean("0")); // true
console.log(Boolean(123)); // true

Implicit Type Casting

When a javascript engine decides to convert the type of any data it is said to be Implicit Type Casting. This happens while using some operations whether it be the relational, assignment, or logical operators, that javascript tends to convert the type of the data in order to give a preferable output. These mainly happen when performing operations between different data types.

console.log(5+"1");  // "51"

Whenever we use another datatype data accompanied with a plus operator and a string data javascript converts the other data which is not a string to a string type data. Here, 5 is the number, and javascript implicitly type cast it to a string. Some other examples are below:

console.log("5"+ null);  // 5null
console.log("5"+ undefined);  // 5undefined
console.log("5" + true);  // 5true

But, when a boolean value is added to a number, it converts it to a number, so the output will also be a number.

console.log(true + 1);  // 2
console.log(1 + false);  // 0

While all other logical operators(-,*,/) type cast the second data to the number or even if both the data are of different data types.

console.log("5" - null);  // 5
console.log("5" * "3");  // 15
console.log(true - false);  // 1
console.log("hashnode"-"hash"); // NaN

Relational operator

== allow type conversion but === does not.

x==y If the type of x is a number and the type of y is a String, return the result of the comparison x == Number(y). If the type of x is a String and the type of y is a Number, return the result of the comparison Number(x) == y. And if x or y is boolean they are also converted to numbers.

console.log(true=="true"); // false

In the above example Number("true") is NaN. Therefore, it returns the output as false.

Unary plus (+) and Unary negation (-)

If it is there with another datatype value like string or boolean it converts it to a Number.

var a=+"123"
console.log(typeof a);
console.log(+"123e-5");  // 0.00123
console.log(+true);  // 1
console.log(+false);  // 0
console.log(+null);  // 0
console.log(+"hello");  // NaN

Also, there is the same condition in the case of Unary negation. The output is obtained after its conversion to a Number.

console.log(-"3");   // -3
console.log(-true);  // -1

Some, other examples:

console.log(4>'8');  // false
console.log(3/null);  // infinity
console.log(true | 0);  // 1

Also, note that infinity is a value defined in javascript.

Type casting in non-primitive datatypes

Every object in javascript has a built-in toPrimitive() method which converts the non-primitive datatype to a primitive value ( [].toPrimitive()). We can't call this method but it works in abstraction. This method is automatically called by a javascript engine whenever we have a non-primitive value and we need a primitive value out of it.

How does this work?

toPrimitive(input,preferredType)

  • If the input is already primitive, return it.
  • Call input.toString(), if the result is primitive, return it.
  • Call input.valueOf(), if the result is primitive, return it.
  • Error.

preferredType : If a preferred type is a Number use valueOf first and then toString. If String, first calls toString and then valueOf.

The boolean of any object is always true even if it's an empty array.

Examples

console.log([] + 1);  // "1"
console.log([].toString());  // ""

As, toString of [] is "" so the result of "" + 1 is "1".

var x=[1,2,3]+ [3,4,5];
console.log(x);  // "1,2,33,4,5"
console.log([]+{});  // "[object Object]"
console.log({}+{});  //  "[object Object][object Object]" 
console.log({}.toString());  // "[object Object]"

Therefore, ""+"[object Object]" is "[object Object]".

console.log([]==0);  // true ([] is "" which converted to a number give 0)
console.log({}==0);  // false (this is because we saw in the above examples that it's not yielding an empty string)