In JavaScript, the toString() method is used to convert a data type to a string. Here are some examples:
- Converting a Number to String:
let num = 42; let strNum = num.toString(); // "42"
- Converting a Boolean to String:
let bool = true; let strBool = bool.toString(); // "true"
- Converting an Array to String:
let arr = [1, 2, 3]; let strArr = arr.toString(); // "1,2,3"
- 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.