Monday, 18 October 2021

Type Conversion



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.


Implicit Conversion:

The implicit conversion of JS automatically converts the data type of the values. This happens in many instances, for example, if a string and number have a ‘+’ operator in between the data type of the number is converted to a string. Similarly, if there is a ‘-’ operator in-between number and string, then the data type of strings are converted to a number.


 

// numeric string used with + gives string type

let result;

 

result = '3' + 2;

console.log(result) // "32"

 

result = '3' + true;

console.log(result); // "3true"

 

// numeric string used with - , / , * results number type

 

let result;

 

result = '4' - '2';

console.log(result); // 2

 

result = '4' - 2;

console.log(result); // 2

 


No comments:

Post a Comment

Array Destructuring

  Destructuring  Destructuring is an ES6/ES2015 feature. Destructuring allows us to break down the complex data structure into a simple data...