Typecasting in JavaScript is the process of converting a value from one data type to another. In that, developers can convert the values of one datatype to another.
There are several ways to perform typecasting in JavaScript:
1. Implicit Typecasting:
JavaScript automatically converts a value from one data type to another as per the requirement. This is known as implicit typecasting or coercion. For example, if you try to add a string and a number, JavaScript will implicitly convert the number to a string and concatenate the two strings.
Example,
let a = 10;
let b = "5";
let c = a + b; // c will be a string "105"
2. Explicit Typecasting:
You can explicitly convert a value from one data type to another using typecasting functions or operators. JavaScript provides several functions and operators for explicit typecasting.
A. parseInt() - converts a string to an integer.
Basically, the parseInt( ) Function is used to convert any Datatype value to an Integer Value.
var a = "10";
var b = parseInt(a); // b will be an integer 10
B. parseFloat() - converts a string to a floating-point number.
parseFloat( ) Function is used to convert any Datatype value to a float value.
var a = "10.5";
var b = parseFloat(a); // b will be a floating-point number 10.5
C. String() - converts a value to a string.
String( ) Function is used to convert any Datatype value to String.
var a = 10;
var b = String(a); // b will be a string "10"
D. Number() - converts a value to a number.
The Number( ) Function is used to convert any Datatype value to a Number
let a = true;
let b = false;
let x = Number(a); // x will be returns 1
let y = Number(a); // y will be returns 0
E. Boolean() - converts a value to a boolean.
Boolean( ) Function is used to convert any Datatype value to a boolean value excepted zero (0) and null.
var a = 10; // a will be true
var b = 0; // b will be false
var c = "Rohan"; // c will be true
F. toString() - converts a value to a string.
Basically, the toString( ) Function also works like the String( ) Function, Which converts any Datatype value to String Value.
var a = ture;
var b = a.toString(); // b will be a string "true"
So these are the types of Explicit Typecasting...
I hope this post will help you to learn Javascript More...!
0 Comments
Please do not add Any Spam link in Comments !