Why do Javascript primitive values (e.g. name = “John”) have properties and methods? [duplicate]

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()) .



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

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"


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.