0

A quick question coming from someone learning JavaScript. So far I am aware that primitive types hold only their value, so why is it I can store a number (a primitive type) and then call the toString method on it as if it were an object? e.g.

let num = 4;
let strNum = num.toString(); /* how is this possible? isn't num just a single piece of data in memory, how can it access this toString method? */
Mysa Mysa
  • 19
  • 1
  • 5
  • When you use a primitive *as if* it were an Object (which it isn't), JavaScript creates a temporary wrapper of the appropriate type. In this case, it's as if you type `new Number(num).toString()` – Pointy Oct 02 '21 at 14:11
  • With a number `.` could also mean "decimal place". You need to disambiguate the expression: `(4).toString()` returns `'4'`. – customcommander Oct 02 '21 at 14:14

0 Answers0