Enthalpy127
Enthalpy127

Reputation: 69

What happens when we treat primitives as objects in JavaScript?

I am learning JS from javascript.info. Now I am currently reading about Methods of primitives.

When we run the following code

let str = 'hello';
alert( str.toUpperCase() ); // HELLO

Internally the following happens (1) creates a special object (2) copies the value of str variable (3) modifies that copied version (4) returns that copied one without touching the original str variable (5) and finally that special object is destroyed.

That's what the author said. But when we have something like this

let str = 'Hello';
console.log(str.toUpperCase());          // HELLO
console.log(str.split('l'));             // (3) ["He", "", "o"]
console.log(str.startsWith('h'));        // false
console.log(str.concat(' JavaScript'));  // Hello JavaScript
console.log(str);                        // Hello

I just want to know that, is a special object created everytime we treat a primitive as an object? From the above code, I am thinking that the whole process(creates an object, do some process and destroyed) is done for 4 times (because I called 4 methods).

Is that true?

And also I read this following from it

The JavaScript engine highly optimizes this process. It may even skip the creation of the extra object at all. But it must still adhere to the specification and behave as if it creates one.

What does it mean? That above lines make me more confuse about how many times the whole process is done.

Upvotes: 3

Views: 194

Answers (1)

Bergi
Bergi

Reputation: 664579

I just want to know that, is a special object created everytime we treat a primitive as an object? I am thinking that the whole process is done for 4 times, because I called 4 methods.

Yes, that's true.

The JavaScript engine highly optimizes this process. It may even skip the creation of the extra object at all. But it must still adhere to the specification and behave as if it creates one.

What does it mean?

It means that creating 4 objects is wasteful - one would suffice, and you'd still get the same result (in this case). The specification is written in a "behave as if" manner, it doesn't govern how an implementation of a javascript engine needs to work step by step, but only what observable behavior it needs to have. If an engine is smart enough to figure out that it can skip one step, such as doing unnecessary copies or creating unused objects, it is allowed to do so as long as the execution result is still the same.

And for method calls on primitive values, that's a relatively simple optimisation - the engine doesn't need to actually allocate an object in memory, it can just skip ahead to the step where the property is looked up on the hypothetical special object.

Upvotes: 2

Related Questions