String Primitives vs String Objects

Blog Home / Author: on June 6th, 2022
String Primitives vs String Objects

String Primitives vs String Objects

Strings are useful for holding data that can be expressed in text form.
In JavaScript, a string is a combination of zero or more characters enclosed in quotes. Depending on how you declare a string, the output may differ. This can cause unwanted bugs or even break your code.

Relatable?

In this post, you’ll learn how JavaScript distinguishes between String objects and primitive string values, broken down into three parts.

Ready? Let’s roll…

What you’ll learn [Summary]:

  1. What are String Primitives?
  2. What are String Objects?
  3. 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");

NOTE: JavaScript automatically converts primitive strings into string objects when a method is invoked on a
primitive string.

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.
See example;

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
primitive string.

However, String objects can be converted to their primitive counterpart using the valueOf() method.

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;

MDN Strings

W3Schools Strings

Stay positive gang ⚡

Leave a Reply

Your email address will not be published.