JavaScript String()
Syntax & Examples
String constructor
The `String` constructor creates a new String object. It performs type conversion when called as a function, rather than as a constructor, which is usually more useful.
Syntax of String
The syntax of String.String constructor is:
new String(thing)
String(thing)This String constructor of String creates a new String object. It performs type conversion when called as a function, rather than as a constructor, which is usually more useful.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
thing | required | The value to convert to a string. |
Return Type
String.String returns value of type String.
✐ Examples
1 Convert number to string
In this example,
- We create a variable
numwith the value 42. - We use the
String()constructor to convert it to a string. - We then log the string representation to the console.
JavaScript Program
void main() {
let num = 42;
let str = String(num);
console.log('String representation of num:', str);
}Output
String representation of num: 42
2 Convert character to string
In this example,
- We create a variable
charwith the value 'A'. - We use the
String()constructor to convert it to a string. - We then log the string representation to the console.
JavaScript Program
void main() {
let char = 'A';
let str = String(char);
console.log('String representation of char:', str);
}Output
String representation of char: A
3 Convert array to string
In this example,
- We create an array
arrwith values [1, 2, 3]. - We use the
String()constructor to convert it to a string. - We then log the string representation to the console.
JavaScript Program
void main() {
let arr = [1, 2, 3];
let str = String(arr);
console.log('String representation of array:', str);
}Output
String representation of array: 1,2,3
Summary
In this JavaScript tutorial, we learned about String constructor of String: the syntax and few working examples with output and detailed explanation for each example.