Programming Tutorials

Using toString() in JavaScript to convert data types to String

By: Nicholas C. Zakas in Javascript Tutorials on 2008-08-15  

In JavaScript, the toString() method is used to convert a data type to a string. Here are some examples:

  1. Converting a Number to String:
    let num = 42;
    let strNum = num.toString(); // "42"
  2. Converting a Boolean to String:
    let bool = true;
    let strBool = bool.toString(); // "true"
  3. Converting an Array to String:
    let arr = [1, 2, 3];
    let strArr = arr.toString(); // "1,2,3"
  4. Converting an Object to String:
    let obj = { name: "John", age: 30 };
    let strObj = obj.toString(); // "[object Object]"

Note that toString() does not work for null or undefined values, and it does not modify the original value. It always returns a new string representation of the original value.

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)