String Primitives vs String Objects
Strings are useful for holding data that can be expressed in text form.
Ready? Let’s roll…
What you’ll learn [Summary]:
- What are String Primitives?
- What are String Objects?
- Overview of String Primitives, String Objects, and the Inconsistencies.
Let’s jump right in…
What are String Primitives?
String literals and strings returned by String calls in a non-constructor context are primitive strings.
See examples below;
const stringOne = "I'm a string primitive"; const stringTwo = 'Also a string primitive'; const stringThree = `Yet another string primitive`; const stringFour = String("I'm a string in a non-constructor context");
What are String Objects?
The strings returned by String calls in a constructor context (that is, called with the new keyword)
are string objects. See below;
const stringObjOne = new String("String object wrapped in double quotes"); const stringObjTwo = new String('String object wrapped in single quotes'); const stringObjThree = new String(`String object wrapped in template literals`);
Overview of String Primitives, String Objects, and the Inconsistencies.
Using the method
eval(), both String primitives and String objects output different results. Primitives passed to
eval() are treated as source code; String objects are treated like any other object by returning the object.
let str1 = '1 + 1' // creates a string primitive let str2 = new String('1 + 1') // creates a String object console.log(eval(str1)) // returns the number 2 console.log(eval(str2)) // returns the string "1 + 1"
For the above reasons, the code may break when it encounters a String object, expecting a
However, String objects can be converted to their primitive counterpart using the
eval(str2.valueOf()) // returns the number 2
It’s a wrap!
Comment below with your thoughts on String objects and primitives.
Leave a link below to articles regarding this matter.
For a deeper dive on strings, check out the links below;
Stay positive gang ⚡
Leave a Reply