In JavaScript, the String() constructor is used to create a new string object. It can be called with or without the new keyword.
Syntax
The syntax for using the String() constructor is as follows:
let str = new String(value);
Parameters
Parameter | Description |
---|---|
value | The value to be converted to a string. If no value is provided, an empty string is created. |
Return Value
The String() constructor returns a new string object.
Examples on JavaScript String() Constructor
Creating a String Object
In this example, we create a string object using the String()
constructor.
let str = new String('Hello, world!'); console.log(str); // Output: "Hello, world!"
Creating an Empty String Object
If no value is provided, the String()
constructor creates an empty string object.
let emptyStr = new String(); console.log(emptyStr); // Output: ""
Creating a String Object from a Number
You can also use the String()
constructor to convert a number to a string.
let num = 123; let str = new String(num); console.log(str); // Output: "123"
Creating a String Object from a Boolean
Similarly, you can convert a boolean value to a string using the String()
constructor.
let bool = true; let str = new String(bool); console.log(str); // Output: "true"
Creating a String Object from an Array
The String()
constructor can also be used to create a string from an array.
let arr = [1, 2, 3]; let str = new String(arr); console.log(str); // Output: "1,2,3"
Creating a String Object from an Object
You can convert an object to a string using the String()
constructor, but the result may not always be what you expect.
let obj = { key: 'value' }; let str = new String(obj); console.log(str); // Output: "[object Object]"
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1 | 3 | 1 |