JavaScript Type Conversions

Alex AnieAlex Anie
10 min read

In JavaScript, when data is converted from one type to another by the JavaScript interpreter, this is referred to as Type Conversion. and this can occur automatically or manually.

There are two ways JavaScript undergoes type conversion, these include;

  • Implicit Conversion (automatically)

  • Explicit Conversion (manually)

But before we take a look at these two methods of Type Conversion, let's see how JavaScript processes data of the same type. This will give us a better understanding of how Type Conversion works.

Evaluating Data of the same Type.

let firstName = 'Alex';
let lastName = 'Anie';

let fullName = firstName +" " +lastName;

console.log(fullName); //-> Alex Anie
console.log(typeof fullName); //-> string

from the code output above, we use the Addition (+) Arithmetic operators to concatenate the firstName and lastName variable and assign it to another variable of fullName. And then we print it out to the console which gave us a value of Alex Anie and using the typeof operator, the fullName returns a string.

What this means is, when JavaScript sees any values put inside single or double quotes, it interprets it as a string and concatenates them together (chaining). But if the values are just numbers without single or double quotes, JavaScript performs an Arithmetic operation on them.

Consider the code below

function age(currentYear, dateOfBirth){
    return currentYear - dateOfBirth;
}

const print = age(2023, 1994);
console.log(print) //-> 29
console.log(typeof print); //-> number

JavaScript evaluates the program above and returns 29 and number as the data type.

Implicit Conversion

Implicit conversion is when JavaScript automatically does a type conversion of values of different data types to a particular data type. For example, converting a string to a number or vice-versa.

Converting string to numbers

In this section, we are going to look at how Javascript implicitly converts strings to numbers with the help of examples.

Type and run the code below.

let print0 = '6' + '3';
let print1 = '6' - '3';
let print2 = '6' -  3;
let print3 =  6 / '3';
let print4 = '6' * '3';
let print5 = '9' % '4';

console.log(print0); //-> 63
console.log(typeof print0); //-> string
//----------------------------------//
console.log(print1); // -> 3
console.log(typeof print1); //-> number
//----------------------------------//
console.log(print2); //-> 3
console.log(typeof print2); //-> number
//----------------------------------//
console.log(print3); //-> 2
console.log(typeof print3); //-> number
//----------------------------------//
console.log(print4); //-> 18
console.log(typeof print4); //-> number
//----------------------------------//
console.log(print5); //-> 1
console.log(typeof print5); //-> number

When the Arithmetic operator is used to evaluate two operands of string data types but number values, JavaScript automatically converts the type to a number after performing the given operation. the Only exception is when addition (+)operator is used as seen in the first examples.

Converting numbers to string

So we have learned how JavaScript automatically converts strings into number types when the value in the string is a number.

In this section, we are going to learn how JavaScript handles Type conversion between a number and a string when the value in the string are letters.

let print0 = 44 + "Hello";
let print1 = 'world' + 52;
let print2 = 44 - "Hello";
let print3 = 21 / "Good Bye";
let print4 = 44 * "Soon";
let print5 = 44 % "Hello";
let print6 = 44 ** "Hello";

console.log(print0) //-> 44Hello
console.log(typeof print0) //-> string
//-------------------------//
console.log(print1) //-> world52
console.log(typeof print1) //-> string
//-------------------------//
console.log(print2) //-> NaN
console.log(typeof print2) //-> number
//-------------------------//
console.log(print3) //-> NaN
console.log(typeof print3) //-> number
//-------------------------//
console.log(print4) //-> NaN
console.log(typeof print4) //-> number
//-------------------------//
console.log(print5) //-> NaN
console.log(typeof print5) //-> number
//-------------------------//
console.log(print6) //-> NaN
console.log(typeof print6) //-> number

The first two variables print0 and print1 had their values concatenated and returned as 44Hello and world52 respectively. That is because text characters and numbers are two different entities and not be mathematically added together with the Addition operator in JavaScript. So JavaScript ends up concatenating them together as one value.

However other values return a NaN. This in JavaScript means Not a Number, meaning it is not a valid number that can be evaluated.

Boolean Type Conversion in (True and False)

Boolean is another set of data types in JavaScript. The Boolean has two values namely: true and false.

Type conversion works differently in Boolean when working with numbers than you would expect.

Consider the code below

let print0 = 44 + true; // 44 + 1
let print1 = 44 - false; // 44 - 0

console.log(print0); //-> 45
console.log(typeof print0); //-> number
//------------------------//
console.log(print1); //-> 44
console.log(typeof print1); //-> number

The Boolean values have a binary representation of 1 and 0, where true is 1 and false is 0.

Now let's see how Boolean values, true and false behave when working with strings.

let print0 = '44' + true; // true = 1
let print1 = '44' - false; // false = 0
let print2 = 'true' - true; // true = 1
let print3 = 'go' - true; // true = 1

console.log(print0); //-> 44true
console.log(typeof print0); //-> string
//-----------------------------------//

console.log(print1); //-> 44
console.log(typeof print1); //-> number
//-----------------------------------//

console.log(print2); //-> NaN
console.log(typeof print2); //-> number
//-----------------------------------//

console.log(print3); //-> NaN
console.log(typeof print3); //-> number

The Boolean values behave just like numbers when used with Arithmetic operators, So when working with Boolean values and Arithmetic operators, treat them as if you are working with 1 and 0.

Null Type Conversion

Null is a primitive value in JavaScript that represents the absence of any object value. This could be when a value is empty or unknown.

Now let's see how type conversion works in null

let print0 = null + 2;
let print1 = null - 8;
let print2 = null - 'null';
let print3 = null + 'Hello World';
let print4 = null / true;
let print5 = null * false;
let print6 = null + true;


console.log(print0); //-> 2
console.log(typeof print0); //-> number
//---------------------------//
console.log(print1); //-> -8
console.log(typeof print1); //-> number
//---------------------------//
console.log(print2); //-> NaN
console.log(typeof print2); //-> number
//---------------------------//
console.log(print3); //-> nullHello World 
console.log(typeof print3); //-> string
//---------------------------//
console.log(print4); //-> 0
console.log(typeof print4); //-> number
//---------------------------//
console.log(print5); //-> 0
console.log(typeof print5); //-> number
//---------------------------//
console.log(print6); //-> 1
console.log(typeof print6); //-> number

A null is an empty object or value as stated earlier, so when we added null + 2, we got 2 in return. This is just like saying add two apples to an empty basket, and then check how many apples are in the basket. The answer we will get is 2 because the basket was empty when we add the 2 apples.

We can also check the type of null by using the typeof operator.

console.log(typeof null) //-> object

As expected. It returns an object.

undefined Type Conversion

Undefined simply means when a variable has not been assigned a value yet. So when you try to access such a variable, it returns a type of undefined.

Let's see how type conversion works with undefined.

let print0 = undefined + 2;
let print1 = undefined - 6;
let print2 = undefined / 10;
let print3 = undefined * 2;
let print4 = undefined ** 2;
let print5 = undefined + undefined;
let print6 = undefined - 'undefined';
let print7 = undefined + 'Hello';

console.log(print0) //-> NaN
console.log(typeof print0) //-> number
//-------------------------//
console.log(print1) //-> NaN
console.log(typeof print1) //-> number
//-------------------------//
console.log(print2)  //-> NaN
console.log(typeof print2) //-> number
//-------------------------//
console.log(print3)  //-> NaN
console.log(typeof print3) //-> number
//-------------------------//
console.log(print4)  //-> NaN
console.log(typeof print4) //-> number
//-------------------------//
console.log(print5) //-> NaN
console.log(typeof print5) //-> number
//-------------------------//
console.log(print6) //-> NaN
console.log(typeof print6) //-> number
//-------------------------//
console.log(print7) //-> undefinedHello
console.log(typeof print7) //-> string

From the code sample above, we got a NaN as an output when we try to add undefined with a number value of 2. What JavaScritp is trying to let us know is that undefined is not a valid number to be added by 2 and this is because undefined does not have any value assigned to it.

To understand more about the type of undefined, we can make use of the typeof operator.

console.log(typeof undefined) //-> undefined

Explicit Conversion

Explicit conversion is when we manually set the type conversion of a JavaScript data type to another data type using the JavaScript built-in methods.

To make an explicit conversion, you can make use of the following constructor based on what you want to convert to.

  • String()

  • Number()

  • Boolean()

String() Explicit Conversion

The String() constructor can be explicitly set to convert data type in JavaScript.

Let's see how this works

let print0 = String(144);
let print1 = String(144 - 140);
let print2 = String(12 * 12);
let print3 = String(144 / 2);
let print4 = String(true);
let print5 = String(null);
let print6 = String(undefined);
let print7 = String(NaN);

console.log(print0) //-> 144
console.log(typeof print0) //-> string
//-------------------------//
console.log(print1) //-> 4
console.log(typeof print1) //-> string
//-------------------------//
console.log(print2) //-> 144
console.log(typeof print2) //-> string
//-------------------------//
console.log(print3) //-> 72
console.log(typeof print3) //-> string
//-------------------------//
console.log(print4) //-> true
console.log(typeof print4) //-> string
//-------------------------//
console.log(print5) //-> null
console.log(typeof print5) //-> string
//-------------------------//
console.log(print6) //-> undefined
console.log(typeof print6) //-> string
//-------------------------//
console.log(print7) //-> NaN
console.log(typeof print7) //-> string

From the code example above, the String() performs the math operation and returns the value as a string however other types such as undefined, null and NaN is returned as a string.

Try this second example

let print0 = (144).toString();
let print1 = (144).toString(2); //Redix of (2) is a binary
let print2 = (true).toString();

console.log(print0); //-> 144
console.log(typeof print0); //-> string
//-------------------------//
console.log(print1); //-> 10010000
console.log(typeof print1); //-> string
//-------------------------//
console.log(print2); //-> true
console.log(typeof print2); //-> string

the toString() method can also be used for type conversion but will true an error when used with null or undefined.

Try the code below.

let print3 = (null).toString();
console.log(print3);
//-> Uncaught TypeError: Cannot read properties of null (reading 'toString')

Number() Explicit Conversion

The Number() method is used to convert values to a number, however, it returns a NaN if the value cannot be converted.

Try the code below.

let print0 = Number('144');
let print1 = Number(true);
let print2 = Number(false);
let print3 = Number(' ');
let print4 = Number(null);

console.log(print0); //-> 144
console.log(typeof print0); //-> number
//-------------------------//
console.log(print1); //-> 1
console.log(typeof print1); //-> number
//-------------------------//
console.log(print2); //-> 0
console.log(typeof print2); //-> number
//-------------------------//
console.log(print3); //-> 0
console.log(typeof print3); //-> number
//-------------------------//
console.log(print4); //-> 0
console.log(typeof print4); //-> number

The above example shows how the Number() method can be used to convert string, Boolean and null to numbers.

Try the second example.

let print0 = Number(undefined);
let print1 = Number(NaN);

console.log(print0); //-> NaN
console.log(typeof print0); //-> number
//-------------------------//
console.log(print1); //-> NaN
console.log(typeof print1); //-> number

Here, the Number() method return undefined and NaN as a NaN with a number type.

Boolean() Explicit Conversion

The data type below returns false when parsed as a value to a Boolean() method

let print0 = Boolean('');
let print1 = Boolean(undefined);
let print2 = Boolean(null);
let print3 = Boolean(0);
let print4 = Boolean(NaN);

console.log(print0) //-> false
console.log(typeof print0) //-> boolean
//------------------------//
console.log(print1) //-> false
console.log(typeof print1) //-> boolean
//------------------------//
console.log(print2) //-> false
console.log(typeof print2) //-> boolean
//------------------------//
console.log(print3) //-> false
console.log(typeof print3) //-> boolean
//------------------------//
console.log(print4) //-> false
console.log(typeof print4) //-> boolean

Other values, expect the above returns true.

let print0 = Boolean(' ');
let print1 = Boolean(1444);
let print2 = Boolean('Say Hello');
let print3 = Boolean('true'); 
let print4 = Boolean(1);

console.log(print0) //-> true
console.log(typeof print0) //-> boolean
//------------------------//
console.log(print1) //-> true
console.log(typeof print1) //-> boolean
//------------------------//
console.log(print2) //-> true
console.log(typeof print2) //-> boolean
//------------------------//
console.log(print3) //-> true
console.log(typeof print3) //-> boolean
//------------------------//
console.log(print4) //-> true
console.log(typeof print4) //-> boolean

Wrapping up

We learned about JavaScript Type Conversions and we discussed the following.

  • Implicit Conversion and Explicit Conversion

Alright! We’ve come to the end of this tutorial. Thanks for taking the time to read this article to completion. Feel free to ask questions. I’ll gladly reply. You can find me on Twitter and other social media @ocxigin. or email me at ocxigin@gmail.com

#Cheers

0
Subscribe to my newsletter

Read articles from Alex Anie directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Alex Anie
Alex Anie

A Frontend Developer | Technical Writer | JavaScript Developer | React.js | Freelancer at LambdaTest Inc. Contact: Twitter @alexanie_ | Email: ocxigin@gmail.com