Chapter 10. String()
Conceptual Overview of Using the String() Object
The String()
constructor function
is used to create string objects and string primitive values.
In the code below, I detail the creation of string values in JavaScript.
<!DOCTYPE html><html lang="en"><body><script> // create string object using the new keyword and the String() constructor var stringObject = new String('foo'); console.log(stringObject); // logs foo {0 = 'f', 1 = 'o', 2 = 'o'} console.log(typeof stringObject); // logs 'object' // create string literal/primitive by directly using the String constructor var stringObjectWithOutNewKeyword = String('foo'); // without new keyword console.log(stringObjectWithOutNewKeyword); // logs 'foo' console.log(typeof stringObjectWithOutNewKeyword); // logs 'string' // create string literal/primitive (constructor leveraged behind the scene) var stringLiteral = 'foo'; console.log(stringLiteral); // logs foo console.log(typeof stringLiteral); // logs 'string' </script></body></html>
String() Parameters
The String()
constructor function
takes one parameter: the string value being created. Below, we create a
variable, stringObject
, to contain the
string value 'foo'
.
<!DOCTYPE html><html lang="en"><body><script> // create string object var stringObject = new String('foo'); console.log(stringObject); // logs 'foo {0="f", 1="o", 2="o"}' </script></body></html>
Note
Instances from the String()
constructor, when used with the new
keyword, produce an actual complex ...
Get JavaScript Enlightenment now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.