DEV Community

Cover image for Type conversion in js
Vigneshwaran V
Vigneshwaran V

Posted on

Type conversion in js

Type Conversion means converting a value from one data type to another in JavaScript.
There are two types:

  • Implicit Type Conversion (Type Coercion) – JavaScript does it automatically.

  • Explicit Type Conversion – You do it manually.

What is DataTypes:

  • In JavaScript, a data type describes the classification of a value that determines what kind of operations can be performed on it. JavaScript is a dynamically typed language, meaning variables are not bound to any specific data type and can change types automatically at runtime.

  • The latest ECMAScript standard defines 8 fundamental data types, which are divided into two main categories: Primitive and Non-Primitive (Reference) types.

1. Primitive Data Types

  • Number
  • String
  • Boolean
  • Undefined
  • Null
  • BigInt
  • Symbol

2. Non-Primitive Data Types

  • Object

  • Array

  • Function

  • Date

  • Map

  • Set

Checking Data Types

Use typeof:

  • In JavaScript, the typeof operator evaluates an operand and returns its data type as a string. It is a unary operator heavily relied on for runtime type checking and handling dynamic values securely.
typeof 42;          // "number"
typeof "hello";     // "string"
typeof true;        // "boolean"
typeof undefined;   // "undefined"
typeof 123n;        // "bigint"
typeof Symbol();    // "symbol"
typeof {};          // "object"
typeof [];          // "object"
typeof function(){} // "function"
Enter fullscreen mode Exit fullscreen mode

Note: typeof null returns "object" due to a historical JavaScript bug.

typeof null; // "object"
Enter fullscreen mode Exit fullscreen mode
  • When JavaScript stores values internally, it keeps a small code (called a type tag) to identify what type of value it is.

  • When JavaScript was created in 1995, the developers made a mistake in how null was represented internally. The binary value used for null looked similar to the one used for objects.

So when typeof checks the type tag, it sees:

typeof null
Enter fullscreen mode Exit fullscreen mode

and incorrectly thinks:

"object"
Enter fullscreen mode Exit fullscreen mode

instead of:

"null"
Enter fullscreen mode Exit fullscreen mode

Yes. This gets into how the first JavaScript engine represented values internally.

A simplified explanation is:

  • Values were stored as a 32-bit binary number.

  • The lowest few bits were used as a type tag.

  • Objects were identified with the tag 000.

Unfortunately, null was represented internally as:

00000000000000000000000000000000
Enter fullscreen mode Exit fullscreen mode

Notice that the last few bits are also:

000
Enter fullscreen mode Exit fullscreen mode

The engine interpreted that tag as:

000 → Object
Enter fullscreen mode Exit fullscreen mode

Imagine JavaScript uses the last 3 bits as type tags:

Now consider:

null = 00000000000000000000000000000000
Enter fullscreen mode Exit fullscreen mode

The last 3 bits are:

000
Enter fullscreen mode Exit fullscreen mode

which matches the Object tag.
So the engine says:

null → tag 000 → object
Enter fullscreen mode Exit fullscreen mode

Implicit Type Conversion (Coercion)

  • Implicit Type Conversion (also called Type Coercion) is when JavaScript automatically converts one data type into another without you writing the conversion code.

Example 1: Number + String

let result = 10 + "5";

console.log(result); // "105"
Enter fullscreen mode Exit fullscreen mode

JavaScript converts 10 (number) into "10" (string) and then concatenates.

"10" + "5" = "105"
Enter fullscreen mode Exit fullscreen mode

Example 2: String - Number

let result = "10" - 5;

console.log(result); // 5
Enter fullscreen mode Exit fullscreen mode

JavaScript converts "10" into 10 and performs subtraction.

10 - 5 = 5
Enter fullscreen mode Exit fullscreen mode

Example 3: String * Number

let result = "10" * 5;

console.log(result); // 50
Enter fullscreen mode Exit fullscreen mode

JavaScript converts "10" to 10

10 * 5 = 50
Enter fullscreen mode Exit fullscreen mode

Example 4: Boolean to Number

console.log(true + 1);  // 2
console.log(false + 1); // 1
Enter fullscreen mode Exit fullscreen mode

Conversion:

true  → 1
false → 0
Enter fullscreen mode Exit fullscreen mode

Example 5: Null Conversion

console.log(null + 5);
Enter fullscreen mode Exit fullscreen mode

Output:

5
Enter fullscreen mode Exit fullscreen mode

Because:

null → 0
0 + 5 = 5
Enter fullscreen mode Exit fullscreen mode

Example 6: Undefined Conversion

console.log(undefined + 5);
Enter fullscreen mode Exit fullscreen mode

Output:

NaN
Enter fullscreen mode Exit fullscreen mode

Because undefined cannot be converted to a valid number.

Difference Between Implicit and Explicit Conversion

Implicit (Automatic)

let result = "10" - 5; // JavaScript converts automatically
Enter fullscreen mode Exit fullscreen mode

Explicit (Manual)

let result = Number("10") - 5;
Enter fullscreen mode Exit fullscreen mode

Here, you explicitly tell JavaScript to convert the string to a number.

  • Implicit conversion = JavaScript does it automatically.

  • Explicit conversion = You do it yourself using functions like Number(), String(), or Boolean().

Explicit Type Conversion in JavaScript

Explicit Type Conversion (also called Type Casting) is when you manually convert a value from one data type to another.

  • JavaScript does not do the conversion automatically—you explicitly tell it to convert.

1. Converting to Number

Use Number():

let str = "123";

let num = Number(str);

console.log(num);        // 123
console.log(typeof num); // "number"
Enter fullscreen mode Exit fullscreen mode

Other Examples

Number("10");      // 10
Number("10.5");    // 10.5
Number(true);      // 1
Number(false);     // 0
Number(null);      // 0
Number(undefined); // NaN
Enter fullscreen mode Exit fullscreen mode

2. Converting to String

Use String():

let num = 100;

let str = String(num);

console.log(str);        // "100"
console.log(typeof str); // "string"
Enter fullscreen mode Exit fullscreen mode

Other Examples

String(123);    // "123"
String(true);   // "true"
String(null);   // "null"
Enter fullscreen mode Exit fullscreen mode

3. Converting to Boolean

Use Boolean():

Boolean(1);      // true
Boolean(0);      // false
Boolean("");     // false
Boolean("Hi");   // true
Boolean(null);   // false
Boolean(undefined); // false
Enter fullscreen mode Exit fullscreen mode

Example:

let value = "Hello";

let result = Boolean(value);

console.log(result); // true
Enter fullscreen mode Exit fullscreen mode

parseInt() and parseFloat()

  • In JavaScript, parseInt() converts a string into a whole integer, while parseFloat() converts a string into a floating-point decimal number. Both functions extract the numeric part from the beginning of a string and discard any trailing text.

  • These are commonly used when converting strings containing numbers.

parseInt("123");     // 123
parseInt("123px");   // 123

parseFloat("12.5");  // 12.5
Enter fullscreen mode Exit fullscreen mode

Example:

let price = "99.99";

console.log(parseFloat(price)); // 99.99
Enter fullscreen mode Exit fullscreen mode

Both Number() and parseInt() can convert strings to numbers, but they behave differently.

Number()

Number() tries to convert the entire string into a valid number.

Number("123");    // 123
Number("12.5");   // 12.5
Number("123px");  // NaN
Enter fullscreen mode Exit fullscreen mode

In "123px", the entire string is not a valid number, so it returns NaN.

parseInt()

parseInt() reads the string from left to right and extracts the integer until it encounters a non-numeric character.

parseInt("123");    // 123
parseInt("12.5");   // 12
parseInt("123px");  // 123
Enter fullscreen mode Exit fullscreen mode

Here:

"123px"
   ↑
parseInt stops at 'p'
Enter fullscreen mode Exit fullscreen mode

So it returns 123.

Example Comparison

console.log(Number("100px"));   // NaN
console.log(parseInt("100px")); // 100
Enter fullscreen mode Exit fullscreen mode

Decimal Numbers

console.log(Number("12.99"));    // 12.99
console.log(parseInt("12.99"));  // 12
Enter fullscreen mode Exit fullscreen mode

parseInt() only returns the integer part.

Top comments (2)

Collapse
 
boopalan-s profile image
boopalan

You wrote with a lot of examples, particularly you gave depth conceptual wise explanation for the typeof null.

Collapse
 
madhanraj profile image
Madhan Raj

Super explanations with examples..