Type Casting in JavaScript

In JavaScript, typecasting refers to the method of transforming a value from one data type into a different data type.

As an illustration, transforming a data type from a number to a string.

What is the data type?

This refers to the category of information that a variable is capable of containing. In JavaScript, there are eight primary data types, which include the following:

Number:

It is a data type that can be any number.

Syntax

Example

let num = 126;

String:

This data type is capable of storing any kind of textual information. The text must be enclosed within quotation marks, which can be either single quotes or double quotes.

Syntax

Example

let str = "Welcome"; //text in double quotes
let str = 'Welcome'; //text in single quotes

Boolean:

This data type can assume just two values: true or false. It is employed to develop features that offer two options, such as yes or no.

Syntax

Example

if(going to the market === true)
console.log("shopping");
if(going to the market === false)
console.log("reading books");

Null:

It holds intrinsic value. It is utilized in scenarios where we intend to indicate the absence of a return value.

Syntax

Example

if(gift) {
	return "ipod";
}
if(prank) {
	return null;
}

Bigint:

This data type is designed to store large numerical values.

Syntax

Example

let num = 12345678912345;

Undefined:

It represents a value in its own right, akin to null. This value is immutable and emerges when a variable is defined but has not been allocated any specific value.

Syntax

Example

let container;
console.log(container); //undefined
container = "pear";
console.log(container); //pear

Symbol:

This is a fundamental data type that signifies a distinct identifier. It is employed as keys for the properties of objects.

Syntax

Example

const mySymbol = Symbol();

Object:

This is a non-primitive or reference data type that specifies various characteristics of an object, including attributes like shape, color, and more.

Syntax

Example

const box = {shape: "rectangle", color: "red", width: "20px", height: "36px"};

Now, let us understand typecasting.

There are two categories of type casting, which are detailed below:

  • Implicit type casting
  • Explicit type casting

Let us understand each one by one.

Implicit type casting

In instances where there is an inherent requirement for type casting, the compiler or interpreter performs this process automatically.

Let us understand it with the help of examples.

Implicit typecasting of strings when some other data type is added to a string

When you concatenate any data type with a string, the data type is automatically transformed into a string. This indicates that if you append a number to a string, it will be converted into a string format. Similarly, if a Boolean value is added to a string, it too will be converted to a string representation.

Code:

Example

let code1 = "Hello" + "there"; //string + string
console.log(code1);
let code2 = "Hello" + 10; //string + number
console.log(code2);
let code3 = "Hello" + false; //string + Boolean
console.log(code3);
let code4 = "Hello" + null; //string + null
console.log(code4);
let code5 = "Hello" + undefined; //string + undefined
console.log(code5);

Output:

Output

Hellothere
Hello10
Hellofalse
Hellonull
Helloundefined

Implicit typecasting of numeric strings to numbers

When a numeric string is involved in a mathematical operation such as multiplication, subtraction, or division with another numeric value, the string representing the number will be automatically transformed into a numerical format.

Note: It does not work with addition (plus).

When one operand is a string that represents a number and the other is an actual numeric value, the string is automatically converted to a number data type.

Code:

Example

let code1 = "5" * 5; 
console.log(code1);
let code2 = "5" - 5; 
console.log(code2);
let code3 = "5" / 5; 
console.log(code3);

Output:

Output

25
0
1

When both values are numeric strings, they are also converted into the number data type.

Code:

Example

let code1 = "10" * "10"; 
console.log(code1);
let code2 = "5" - "10"; 
console.log(code2);
let code3 = "5" / "10"; 
console.log(code3);

Output:

Output

100
-5
0.5

Implicit typecasting of Boolean to numbers

When one value is a numerical type and the other is of Boolean type.

Code:

Example

let code1 = 2 + true; 
console.log(code1);
let code2 = 2 + false; 
console.log(code2);

Output:

When one operand is represented as a numeric string and the other as a Boolean, the resultant combination is converted into a string format.

Code:

Example

let code1 = "2" + true; 
console.log(code1);
let code2 = "2" + false; 
console.log(code2);

Output:

Output

2true
2false

When executing arithmetic operations involving Boolean values.

Numeric Value - Boolean

Code:

Example

let code1 = 10 - true; 
console.log(code1);
let code2 = 10 - false; 
console.log(code2);

Output:

Numeric String - Boolean

Example

let code1 = "10" - true; 
console.log(code1);
let code2 = "10" - false; 
console.log(code2);

Output:

Number / Boolean

Example

let code1 = 10 / true; 
console.log(code1);
let code2 = 10 / false; 
console.log(code2);

Output:

Output

10
Infinity

Numeric String / Boolean

Example

let code1 = "10" / true; 
console.log(code1);
let code2 = "10" / false; 
console.log(code2);

Output:

Output

10
Infinity

Number * Boolean

Example

let code1 = 10 * true; 
console.log(code1);
let code2 = 10 * false; 
console.log(code2);

Output:

Numeric String * Boolean

Example

let code1 = "10" * true; 
console.log(code1);
let code2 = "10" * false; 
console.log(code2);

Output:

Implicit typecasting of null to a number

Performing arithmetic operations involving a number in conjunction with a null value can lead to interesting outcomes. When a null is encountered alongside numbers, it behaves as if it is equivalent to 0.

Code:

Example

const code1 = 2 + null; 
console.log(code1);
const code2 = 2 - null; 
console.log(code2);
const code3 = 2 * null; 
console.log(code3);
const code4 = 2 / null; 
console.log(code4);

Output:

Output

2
2
0
Infinity

Implicit typecasting of undefined

Number with Undefined

Performing mathematical computations on a variable that has not been assigned a value.

Code:

Example

const code1 = 2 + undefined; 
console.log(code1);
const code2 = 2 - undefined; 
console.log(code2);
const code3 = 2 * undefined; 
console.log(code3);
const code4 = 2 / undefined; 
console.log(code4);

Output:

Output

NaN
NaN
NaN
NaN

Null with Undefined

Performing arithmetic operations involving an undefined value alongside null.

Code:

Example

const code1 = null + undefined; 
console.log(code1);
const code2 = null - undefined; 
console.log(code2);
const code3 = null * undefined; 
console.log(code3);
const code4 = null / undefined; 
console.log(code4);

Output:

Output

NaN
NaN
NaN
NaN

Boolean with Undefined

Performing arithmetic operations on an undefined value in conjunction with Boolean values.

Code:

Example

const code1 = true + undefined; 
console.log(code1);
const code2 = false - undefined; 
console.log(code2);
const code3 = true * undefined; 
console.log(code3);
const code4 = false / undefined; 
console.log(code4);

Output:

Output

NaN
NaN
NaN
NaN

Explicit type casting

In scenarios where there is an external requirement for type conversion, it is performed manually. This explicit type conversion can be achieved through the utilization of built-in methods.

Explicit type casting to a number

The number function allows us to convert any value into a numeric type.

Numeric String to a Number

Code:

Example

const code1 = Number("6"); 
console.log(code1);

Output:

String to a Number

Example

const code1 = Number("Hello"); 
console.log(code1);

Output:

Boolean to a Number

Example

const code1 = Number(true); 
console.log(code1);
const code2 = Number(false); 
console.log(code2);

Output:

Null to a Number

Example

const code1 = Number(null); 
console.log(code1);

Output:

Undefined to a Number

Example

const code1 = Number(undefined); 
console.log(code1);

Output:

Empty string to a Number

Example

const code1 = Number(' '); 
console.log(code1);

Output:

Explicit type casting to string

We have the option to employ either the String function or the toString method to convert any value into a string format.

Null to a String

Example

const code2 = String(null); 
console.log(code2);
const code1 = (null).toString(); 
console.log(code1);

Output:

Output

null
TypeError

Number to a String

Example

const code1 = (5).toString(); 
console.log(code1);
const code2 = String(5); 
console.log(code2);

Output:

Undefined to a String

Example

const code1 = String(undefined); 
console.log(code1);
const code2 = (undefined).toString(); 
console.log(code2);

Output:

Output

undefined
TypeError

NaN to a String

Example

const code1 = String(NaN); 
console.log(code1);
const code2 = (NaN).toString(); 
console.log(code2);

Output:

Output

NaN
NaN

Boolean to a String

Example

const code1 = String(true); 
console.log(code1);
const code2 = (false).toString(); 
console.log(code2);
const code3 = String(false); 
console.log(code3);
const code4 = (true).toString(); 
console.log(code4);

Output:

Output

true 
false
false
true

Explicit type casting to Boolean

The Boolean function can be employed to transform any data type into a Boolean value.

Explicit type casting to false

Example

const code1 = Boolean(undefined); 
console.log(code1);
const code2 = Boolean(null); 
console.log(code2);
const code3 = Boolean(0); 
console.log(code3);
const code4 = Boolean(NaN); 
console.log(code4);
const code5 = Boolean(""); 
console.log(code5);

Output:

Output

false
false
false
false
false

Explicit type casting to true

Example

const code1 = Boolean("Hello"); 
console.log(code1);
const code2 = Boolean(" "); 
console.log(code2);
const code3 = Boolean(1); 
console.log(code3);

Output:

Output

true
true
true

Explicit type casting arrays to objects

There are several techniques available for transforming arrays into objects.

Using the spread operator

The spread operator can be utilized to transform an array into an object.

Code:

Example

let myArray = ["HTML", "JS", "CSS", "Java", "Python", "SQL"];
let myObject = {...myArray};
console.log(myObject);

Output:

Output

{
  '0': 'HTML',
  '1': 'JS',
  '2': 'CSS',
  '3': 'Java',
  '4': 'Python',
  '5': 'SQL'
}

Using the for loop

We can utilize a for loop to transform the array into an object.

Code:

Example

let myArray = ["HTML", "JS", "CSS", "Java", "Python", "SQL"];
let myObject = { };
let arrToObj = (arr) => {
	for ( let i = 0; i < arr.length; i++) {
	myObject[i] = arr[i];
}
return myObject;
}
console.log(arrToObj(myArray));

Output:

Output

{
  '0': 'HTML',
  '1': 'JS',
  '2': 'CSS',
  '3': 'Java',
  '4': 'Python',
  '5': 'SQL'
}

Using the forEach loop

The forEach loop can be utilized to transform an array into an object.

Code:

Example

let myArray = ["Book1", "Book2", "Book3", "Book3", "Book4", "Book5"];
let myObject = { };
myArray.forEach((item, index) => {
	myObject[index] = item;
})
console.log(myObject);

Output:

Output

{
  '0': 'Book1',
  '1': 'Book2',
  '2': 'Book3',
  '3': 'Book3',
  '4': 'Book4',
  '5': 'Book5'
}

Using the Object.assign

The Object.assign function can be utilized to transform an array into an object.

Code:

Example

let myArray = ["Book1", "Book2", "Book3", "Book4", "Book5", "Book6"];
let myObject = Object.assign({ }, myArray);
console.log(myObject);

Output:

Output

{
  '0': 'Book1',
  '1': 'Book2',
  '2': 'Book3',
  '3': 'Book4',
  '4': 'Book5',
  '5': 'Book6'
}

Using the Object.fromEntries

The Object.fromEntries function allows us to transform an array into an object.

Code:

Example

let myArray = [[0, "cartoon1"], [1, "cartoon2"], [3, "cartoon3"], [4, "cartoon4"]];
let myObject = Object.fromEntries(myArray);
console.log(myObject);

Output:

Output

{ '0': 'cartoon1', '1': 'cartoon2', '3': 'cartoon3', '4': 'cartoon4' }

Explicit type casting objects to arrays

Utilizing built-in methods, we can transform objects into arrays.

Using the Object.entries

The Object.assign method can be utilized to transform an array into an object.

Code:

Example

let myObject = {
0: "BMW",
1: "Audi",
2: "Ford",
3: "Honda"
}
let myArray = Object.entries(myObject);
console.log(myArray);

Output:

Output

[ [ '0', 'BMW' ], [ '1', 'Audi' ], [ '2', 'Ford' ], [ '3', 'Honda' ] ]

Using the Object.values

The Object.values function can be utilized to transform arrays into objects.

Code:

Example

let myObject = {
0: "BMW",
1: "Audi",
2: "Ford",
3: "Honda"
}
let myArray = Object.values(myObject);
console.log(myArray);

Output:

Output

[ 'BMW', 'Audi', 'Ford', 'Honda' ]

Conclusion:

We have understood type casting in JavaScript in this article. The following are the points to remember:

  • There are eight main data types in JavaScript: Number, String, Boolean, Null, Bigint, Undefined, Symbol and Object.
  • There are two types of type casting: implicit and explicit.
  • Implicit type casting means the internal conversion of one data type to another by the compiler or the interpreter.
  • Explicit type casting means the external conversion of one data type to another manually using built-in methods.

Input Required

This code uses input(). Please provide values below: