Primitive Wrapper Types in JavaScript

🔍 What Are Primitive Wrapper Types?

In JavaScript, primitive values like string, number, and boolean are not objects. However, JavaScript allows us to treat them like objects temporarily by using built-in wrapper types:

  • String → wraps string
  • Number → wraps number
  • Boolean → wraps boolean

Note

These wrappers enable access to useful methods on primitive types.

💡 How It Works

When you access a property or method on a primitive, JavaScript:

  • Creates a temporary object using the wrapper constructor
  • Calls the method on that object
  • Discards the object immediately afterward

Code Snippet

const str = "hello";
console.log(str.toUpperCase()); // "HELLO"

// Behind the scenes:
const temp = new String("hello");
console.log(temp.toUpperCase());

📘 Examples

String Wrapper

const text = "Hi";
console.log(text.length); // 2
console.log(text.charAt(0)); // "H"

Number Wrapper

const num = 42;
console.log(num.toFixed(2)); // "42.00"

Boolean Wrapper

const isTrue = true;
console.log(isTrue.toString()); // "true"

⚠️ Don't Use Wrapper Constructors Manually

It's generally a bad idea to explicitly create wrapper objects with new String(), new Number(), or new Boolean(). These are objects, not primitives, and behave differently.

Code Snippet

const strObj = new String("hello");
console.log(typeof strObj); // "object"
console.log(strObj === "hello"); // false

Note

Use primitive literals instead of wrapper constructors to avoid bugs.

🧠 Summary

  • Primitive wrapper types provide object-like behavior to primitives.
  • They are created temporarily by the JS engine when needed.
  • Avoid using new String(), new Number(), etc. explicitly.
>>“JavaScript gives primitives object-like powers through automatic wrapping.”

🔗 References