JavaScript Auto-Boxing Explained: Calling Methods on Primitives

If strings in JavaScript are primitives, how can we call methods like .split()? "hello".split("") At first this looks strange, because primitives are not objects. The reason it works is because JavaScript does something behind the scenes called auto-boxing. When you call a method on a string, JavaScript temporarily wraps the primitive into a String object, runs the method, and then removes the object. That’s why primitives like strings can still use methods. And this also explains this behavior "hello" === new String("hello") // false Because one is a primitive and the other is an object. #javascript

To view or add a comment, sign in

Explore content categories