There are two types of data types in Javascript
1) Primitive types
2) Non-primitive types (object references)
Primitive types: Primitives are known as being immutable data types because there is no way to change a primitive value once it gets created.
Non-primitive types: Non-primitive values are mutable data types. Objects can store data, and collections of their properties are mutable.
Let's first understand what a method is.
Methods: Methods are functions stored as properties of objects. Primitive values don't directly contain methods, but JavaScript temporarily wraps most primitives in corresponding object wrappers when property access occurs.
Did you notice something...
Primitives are immutable, while methods are typically associated with objects.
But even then we have built-in methods in javascript for primitive data types.
So how does it work? Let's find out..
All primitive types, except null and undefined, have their corresponding object wrapper types, which provide useful methods for working with the primitive values.
When a property or method is accessed on a primitive value, JavaScript automatically wraps the value into the corresponding wrapper object and accesses the property on the object instead.
Here's how JavaScript handles methods for primitive values using object wrapper types:
1. Primitive Value Handling:
When you try to call a method on a primitive value directly, JavaScript recognizes the attempt to use a method on a value that doesn't inherently have methods.
To provide the necessary functionality, it performs a temporary conversion of the primitive value into its corresponding object wrapper type.
This conversion happens behind the scenes, without you explicitly creating the wrapper object yourself.
2. Wrapper Object Creation:
- JavaScript creates a wrapper object that encapsulates the primitive value.
- This wrapper object has the same value as the primitive but belongs to the object wrapper type (e.g., Number, String, Boolean, BigInt, Symbol).
nullandundefinedare the only primitive values that do not have object wrappers. - The wrapper object has the methods associated with its type, allowing you to perform operations on the primitive value.
3. Method Execution:
- The method you called is then executed on the wrapper object. The method can read the primitive value and return a derived result. Since primitives are immutable, the original value is never modified.
- Once the method finishes execution, the wrapper object is discarded.
- The original primitive value remains unchanged, as it was never directly modified.
let name = "akshay";
let myName = name.toUpperCase(); // Calls toUpperCase() on the primitive string "akshay"
console.log(myName); // Output: "AKSHAY"
console.log(name); // Output: "akshay"
console.log(typeof name); // Output: "string" (still a primitive)

Top comments (0)