In our previous article , we discussed that JavaScript has not only objects but also primitive types. We also mentioned that primitive types do not have properties or methods since they are not objects.
However, let's test this point to confirm whether it is true or not. Try running this code in your editor:
const name = "john";
console.log(name.length);
The output will be 4, which refers to the number of characters in the string. But wait, didn't we just say that primitive data types don't have properties? π π π π
Autoboxing
Don't worry, there is an explanation for this π π. Although primitive values don't have properties or methods, JavaScript uses the concept of autoboxing to create a temporary object wrapper around the value when we use a property or method on a primitive value.
So, when we use the .length property on the string primitive name, JavaScript automatically creates a temporary String object wrapper around the value "john", which allows us to access the .length property.
We should note that this object is a built-in object in JavaScript, and there are many predefined objects such as String, Boolean, Date, and Math. JavaScript detects the type of primitive data that we create and automatically creates an object that corresponds to that data type. For example, since we created a string primitive in our example, the object created by JavaScript is a String object.
manual boxing
We can also perform manual boxing ourselves. Here's an example:
let firstName = String("naima");
console.log(firstName.length);
console.log(name.valueOf()); // "john"
In this example, we create an object directly without using autoboxing, and we can retrieve our primitive value using the valueOf() method.
I hope this article helps to clear up the confusion that exists around primitive types in JavaScript
Top comments (0)