JavaScript Objects: Uncovering the Truth Behind Autoboxing

Why do people say “Everything in JS is an object” ?? Does that mean primitive datatypes like string, number, and boolean are objects too? But wait… const str = "hello" console.log(typeof str) // "string" It clearly says "string" — not "object". So where is the object? The answer is hidden in proto. If you check: str.proto You will see an object that contains all the methods we use on strings: • at() • charAt() • includes() • indexOf() • toUpperCase() • length and many more… That object is String.prototype. So what’s happening behind the scenes? When you use: "hello".toUpperCase() JavaScript temporarily wraps the primitive string into an object like this: "hello" → new String("hello") This wrapper object is linked to String.prototype, and that’s how you can access string methods. Then why is typeof "hello" not "object"? Because the actual value is still a primitive. JavaScript just gives it temporary access to an object through the prototype chain. This mechanism is called autoboxing. So when people say “Everything in JS is an object”, what they really mean is: • Objects inherit from Object.prototype • Arrays inherit from Array.prototype • Functions inherit from Function.prototype • Even primitives are linked to their wrapper prototypes • Everything (except null and undefined) connects to an object internally JavaScript is prototype-based. Check out the screenshots I attached — you’ll see the prototype object containing all string methods. "So interestingly, this also allows us to modify the methods and properties of a datatype. Because all strings are linked to String.prototype, if you change something inside that prototype, it affects every string in your application." If you want to know more about Objects in JavaScript, read this blog: https://lnkd.in/dmMDv939 #javascript #javascriptObject #chaicode #chaiaurcode

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories