2

I am learning difference between primitive and reference datatypes in JS and am confused by primitive values because on one hand primitive values have no properties or methods but on the other hand I am able to perform properties or methods like length or trim() on primitive types (e.g "John".length or "John".toUpperCase()) .

Andy
  • 541
  • 2
  • 4
  • 14

2 Answers2

2

They don't. Primitive values have neither properties nor methods.

But when you do

var s = " a ";
var b = s.trim();

the value of s is promoted to a String object (not a primitive string) just for this operation.

It's the same for numbers and booleans.

You can check you don't really attach properties to primitive values with this code :

var s = "a";
s.prop = 2;
console.log(s.prop); // logs undefined

It logs undefined because the property was attached to a temporary object, an instance of String, not to s. If you wanted to keep the property, you'd have done

var s = new String("a");
s.prop = 2;
console.log(s.prop); // logs 2
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

They don't. However, whenever you access a property (method) on them they're implicitly casted to a wrapper object.

var name = "John";
name.toLowerCase(); // typeof name == "string"
// what happens is:
(new String(name)).toLowerCase() // typeof new String(name) == "object"
Bergi
  • 630,263
  • 148
  • 957
  • 1,375