Methods of Primitives in JavaScript
In JavaScript, primitive values like string
, number
, and boolean
act like objects because JavaScript provides them with methods. But how does that work? Let’s dive in!
1️⃣ What Are Primitives?
Primitives are the basic data types in JavaScript:
✅ String → "Hello"
✅ Number → 42
✅ Boolean → true
/ false
✅ Symbol → Symbol("id")
✅ BigInt → 123n
✅ Null & Undefined (⚠️ No methods on these)
📌 Important: Primitives are NOT objects, but JavaScript temporarily wraps them in objects when you call methods.
2️⃣ How Can Primitives Have Methods?
When you use a method on a primitive (like "Hello".toUpperCase()
), JavaScript does the following behind the scenes:
1️⃣ Wraps the primitive in a temporary object (like new String("Hello")
)
2️⃣ Calls the method on this temporary object
3️⃣ Deletes the temporary object immediately
Example:
📌 Objects stay in memory, but temporary wrapper objects disappear instantly.
3️⃣ Methods of Different Primitives
🔹 String Methods
🔹 Number Methods
🔹 Boolean Methods
Since true
and false
are primitives, they don't have many built-in methods, but they can be converted to strings or numbers.
🔹 Symbol Methods
Symbols are unique and used as property keys.
🔹 BigInt Methods
BigInt allows working with large numbers beyond Number.MAX_SAFE_INTEGER
.
4️⃣ Special Cases: null
and undefined
🚫 null
and undefined
don’t have methods because they aren’t objects.
📌 Always check for null
or undefined
before calling methods.
5️⃣ Summary
✔ Primitives behave like objects temporarily
✔ JavaScript wraps them in temporary objects to allow method calls
✔ Strings, Numbers, Booleans, Symbols, and BigInts have useful methods
✔ null
and undefined
have no methods
🚀 Now you understand how primitives work with methods! Let me know if you need more examples. 😊