The toString() method is a fundamental feature in JavaScript that converts a value to its string representation. It’s a method you can use for numbers, booleans, arrays, and objects. One of the most common uses of toString() is to convert a number to its string representation. Here’s an example:

const num = 10;
console.log(num.toString()); // "10"

This method accepts an optional ==radix== which is a number from 2 to 36. This radix represents the base, such as base 2 for binary or base 8 for octal. If the radix is not specified it defaults to base 10, which is decimal. Here’s an example of passing 2 as an argument to the toString() method:

const num = 10;
console.log(num.toString(2)); // "1010"

The result will be 1010 which is the binary representation for the decimal number 10.

You can also use the toString() method to convert arrays and objects to strings. Arrays have a custom implementation of toString() that converts each element to a string and joins them with commas. Here’s an example:

const arr = [1, 2, 3];
console.log(arr.toString()); // "1,2,3"

In this example all the elements of the array are joined together to form the string 1,2,3.

When toString() method is used with objects, the result will not be a stringified version of the object properties.

const person = {
  name: "John",
  age: 30,
  isStudent: true
},
 
console.log(person.toString()); // "[object Object]"

In this example, the result will be the default string representation for the object which is [object Object]. To get a stringified version of the person object properties you’ll need to use JSON.stringify() which you will learn about more in the future lecture videos.

In conclusion, the toString() method is used for converting values to strings. Understanding how it works with different data types and how to customize it for your own objects can greatly advance your ability to manipulate and display data in your JavaScript applications.