Type Conversion
Converting the datatype of a value in javascript is type conversions.
- Converting a value to string
- Converting a value to number
The most commonly used type conversions are
Converting a value to string:
String() or toString() methods are used to convert the variable/value to a string.
Syntax : String(value); / Value.toString();
const a = 155;
const b = String(a);
const c = a.toString();
console.log(typeof a, typeof b, typeof c)// number string string
Converting a value to a number:
The number () method is used to convert the value into a number. If the value is complete/has an alphabet or special characters
in between the value, it will return NaN (Not a Number). It can convert all numeric text or boolean values to number.
Syntax: Number(value);
const a = "55";
const b = "B";
const c = true;
const d = false;
console.log(typeof a, typeof b, typeof c, typeof d);// string string boolean boolean
const e = Number(a);
const f = Number(b);
const g = Number(c);
const h = Number(d);
console.log(typeof e, f, g, typeof h)//number NaN 1 number
The above-mentioned methods are explicit conversion (i.e) the data type of the value converted manually.
There are instances in the javascript that convert the data type of the value. This type of conversion is implicit conversions.
There are instances in the javascript that convert the data type of the value. This type of conversion is implicit conversions.
No comments:
Post a Comment