JavaScript - TypedArray toString() Method
The JavaScript TypedArray toString() method returns a string representation of the current typed array and its elements. JavaScript calls the toString method automatically when a typed array is to be represented as a text value, e.g. when a typed array is concatenated with a string.
Note − It converts a typed array to a string implicitly, which means that the typed array is automatically changed by the JavaScript engine.
Syntax
Following is the syntax of JavaScript TypedArray toString() method −
toString()
Parameters
It does not accept any parameters.
Return value
This method returns a string representation of the elements of the typed array.
Examples
Example 1
In the following example, we are using the JavaScript Typedarray toString() method to retrieve a string representation of a typed array: [1, 2, 3, 4, 5].
<html>
<head>
<title>JavaScript TypedArray toString() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([1, 2, 3, 4, 5]);
document.write("Typed array: ", T_array);
//using toString() method
let str = T_array.toString();
document.write("<br>String representating typed array: ", str);
document.write("<br>Type of str(after converting to a string): ", typeof(str));
</script>
</body>
</html>
Output
The above program returns a string representing a typed array −
Typed array: 1,2,3,4,5 String representating typed array: 1,2,3,4,5 Type of str(after converting to a string): string
Example 2
The following is another example of using the JavaScript TypedArray toString() method to explicitly convert the typed array [10, 20, 30, 40, 50, 60, 70, 80] into a string. Additionally, we'll look an implicit method to achieve the same result.
<html>
<head>
<title>JavaScript TypedArray toString() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([10, 20, 30, 40, 50, 60, 70, 80]);
document.write("Typed array: ", T_array);
//using toString() method
//explicit conversion
let str = T_array.toString();
document.write("<br>String representating typed array(explicit): ", str);
document.write("<br>Type of str(after converting to a string): ", typeof(str));
//implicit conversion
let new_str = `${T_array}`;
document.write("<br>String representating typed array(implicit ): ", new_str);
document.write("<br>Type of str(after converting to a string): ", typeof(new_str));
</script>
</body>
</html>
Output
After executing the above program, it will return a string representation typed array:
Typed array: 10,20,30,40,50,60,70,80 String representating typed array(explicit): 10,20,30,40,50,60,70,80 Type of str(after converting to a string): string String representating typed array(implicit ): 10,20,30,40,50,60,70,80 Type of str(after converting to a string): string