Sobes.tech
Middle

Γιατί είναι δυνατό να προσεγγίσουμε μια πρωτόγονη συμβολοσειρά στη JavaScript σαν να είναι αντικείμενο;

sobes.tech AI

Απάντηση από AI

In JavaScript, when accessing a primitive string string (not String), an automatic conversion (boxing/wrapping) occurs into a String object. This is a temporary object that contains methods and properties accessible for strings (e.g., .length, .toUpperCase(), .indexOf()). After the operation on this temporary object, it is destroyed.

For example:

// primitive string
const myString = "hello";

// Accessing the .length property on the primitive string
// Automatically wrapped into a String object { "hello" }
// Then, the .length property is called on this temporary object
console.log(myString.length); // 5

// Accessing the .toUpperCase() method on the primitive string
// Automatically wrapped into a String object { "hello" }
// Then, the .toUpperCase() method is called on this temporary object
console.log(myString.toUpperCase()); // "HELLO"

// After the operation, the temporary object is destroyed.
// myString remains a primitive string.
console.log(typeof myString); // "string"

This behavior makes working with primitive types easier, allowing object-oriented syntax to access their functionality without explicitly creating wrapper objects.

Comparison between a primitive string and a String object:

Characteristic Primitive string ("string") String object (new String("string"))
Type string object
Comparison with === By value By reference
General More performant Less performant
Usage Preferred To be avoided unless explicitly needed