December 2012
Beginner
164 pages
3h 15m
English
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>
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>
Instances from the String()
constructor, when used with the new keyword, produce an actual complex ...
Read now
Unlock full access