DEV Community

Cover image for How are METHODs used in primitive types in JavaScript?
Akshay Kant
Akshay Kant

Posted on

How are METHODs used in primitive types in JavaScript?

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 also understand, what is a method?

Methods: A method is a special kind of function that is associated with an object. It's a property of an object that holds a function definition, allowing you to perform specific actions on the object's data.

Did you notice something...
Primitive type and immutable data and methods are associated with objects.
But even then we have built-in methods in javascript for primitive data types.
So how does it work!!, Let's learn..

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 is accessed on a primitive value, JavaScript automatically wraps the value into the corresponding wrapper object and accesses the property on the object instead.

object wrapper types

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).
  • 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 access and manipulate the primitive value through the wrapper object's properties.
  • 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)


Enter fullscreen mode Exit fullscreen mode

Top comments (0)