In previous modules you have been used to working with strings literals like this:
const greeting = "Hello, World!";
But JavaScript also has string objects. Both string objects and string primitives are used to handle text but they function differently under the hood. A string object is created using the string constructor function, which wraps the primitive value in an object. Here is how you would create a string object:
const greetingObject = new String("Hello, World!");
console.log(typeof greetingObject); // "object"
When we use the typeof
operator we can see that the result is of type object instead of type string. One of the things that you might have been wondering about is how you can use properties like the .length
property on string primitives.
When you use the length
property on a string primitive, JavaScript temporarily wraps the string primitive in a string object, to perform the operation. This is why you can use the length
property and the different methods like repeat()
, concat()
, and slice()
. These types of methods and properties are referred to as instance methods also properties and static methods. You will learn about how that works in detail in future modules.
One key difference between a string object and a string primitive is how it relates to memory and performance. String primitives are usually more memory efficient and faster compared to string objects. Although you will primarily work with string primitives in your code, it’s still useful to understand how string objects work.