0

I'm confused with Javascript's prototype property. See the below Code.

var s = 12;
var s1 = new String();

console.log(s.constructor);  // Outputs: Number() { [native code] } 
console.log(s instanceof String); // Outputs: false
console.log(s instanceof Object); // Outputs: false
//console.log(toString() in s);   
console.log(s.isPrototypeOf(Object)); // Outputs: false
//console.log(s.prototype.isPrototypeOf(Object));

console.log(s.hasOwnProperty ("toString")); // Outputs: false

console.log(s.toString()); // // Outputs: 12
// My Question is how does toString() function is been called, where does it falls int the prototype chain. Why is it not showing undefined.

console.log(s1.constructor); // Outputs: Number() { [native code] } 
console.log(s1 instanceof String); // Outputs: true

I understand that when we create an object by using {} or constructor (new String()) above, it inherits from Object.prototype. And thats why console.log(s1 instanceof String); // Outputs: true and thus we're able to call toString() on s1. But i'm confused with what happens in the case of var x = "someString" or var x = something.

Thanks for your time.

1 Answer 1

1

There's a difference between string primitive values (like "hello world") and String objects. Primitive types — strings, numbers, booleans — are not objects.

When primitive values are used like objects, with the . or [] operators, the runtime implicitly wraps the values in objects via the corresponding constructors (String, Number, Boolean). Primitive values don't have properties, but because of that automatic wrapping you can do things like

var n = "hello world".length;

and it works.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that makes sense now, Just one more question, Is it correct if I say premitive types don't have prototype property or no property at all, it's just the implicit conversion that allows them to call the desired property if applicable.
@nitte93user3232918 yes that's correct - primitive values are not objects, so they have none of the things objects have (like a prototype).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.