How to convert integer to string in javascript example

Convert String to integer  examples

Learn how to do String to Integer conversion. Now we will walk through the Integer to String conversion in javascript. This is a basic example tutorial from Number to String conversion where numbers can be integers and float values conversion of integers to string is a common and basic task for web developers.

How to convert String to integer in javascript examples?

We have different approaches to convert to String object This article explains the different approaches to achieve it.

  • String function declaration
  • Append the empty string
  • using toString() method

String function syntax

String(number) :

The string function accepts any primitive value as a parameter that returns a primitive value. if the integer value is supplied as input, and output integer. This internally calls the toString method to convert to String. Please note that String function and String constructor. String construction is created using new String() syntax which returns an object. Please see the below examples for more understanding

var stringType =  String(51);//  String function returns String data type  
var objectDataType = new  String(51);// String constructor returns Object data type  
var numbertype =  String(51);// valid and returns 51 as number not string  
var undefinedString = String(undefined) // valid and returns "undefined" as string  
var nullString = String(null) // valid and returns "null" as string  
var numbertype = String(true) // valid and returns "true" as string  

Append an empty string to a number using plus operator

any primitive value type can be converted to a string object by appending an empty string. The conversion process is less illustrative.

var stringNumber =undefined +''     // valid and returns undefined as string type  
var stringNumber =null +''     // valid and returns null as string type  
var stringNumber =12 +''     // valid and returns 12 as string  
var stringNumber =''+43     // valid and returns 43 as string  

Using toString() function

The above two approaches internally call toString() method. Any primitive value can be converted to a String using this approach.

var number1=123;  
var number2=null;  
var number3=undefined  
number1.toString() //valid and returns "123" as string type  
number2.toString() //Not Valid gives compile error like Cannot read property 'toString' of null  
number3.toString() //Not Valid gives compile error like Cannot read property 'toString' of undefined  

the exception “Cannot read property ’toString’ of undefined/null” was solved by not calling the toString() method for null and undefined values

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.