Where do primitive data types get methods (e.g., .toString() and others) from?
sobes.tech AI
Answer from AI
Primitive data types in JavaScript (strings, numbers, booleans, Symbol, BigInt, null, undefined) do not actually have methods. However, when we try to call a method on a primitive value, JavaScript temporarily wraps it in the corresponding object wrapper (String, Number, Boolean, Symbol, BigInt).
For example, when calling .toString() on the string 'hello', JavaScript creates a temporary object new String('hello'), calls the toString() method of this object, and then destroys the temporary object. This mechanism is called autoboxing or automatic boxing.
The data types null and undefined do not have corresponding object wrappers and therefore cannot have methods. Attempting to call a method on null or undefined will result in a TypeError.