1. javaScript

Wrapper Object in JavaScript

In JavaScript, an object is just a collection of properties and values. In order to invoke a property of an object, you can just use .propertyname after object name. Moreover in case if value of a property is function then that’s called a method.

In call a method on an object(let’s say object Computer) you can just say Computer.methond()

It’s quite simple. But there’s a lot going on under the hood, as JavaScript is taking a Primitive Data Type(String, Boolean) and is converting it into an Object and then is calling a method on it. Note that you cannot call a method on Primitive Data Types as these are immutable.

So what happen there is that JavaScript would take Primitive Data Type(let’s say string s) and call new String(s), then take this new object and call method on it.

Explaining Wrapper Object in JavaScript using an illustration
Illustrating Wrapper Object in JavaScript

There does exist wrapper creating functions for other primitive data types as well. These are –

  • Number() for numbers
  • Boolean() for Booleans
  • String() for strings

    Note that there isn’t any Wrapper Object for null or undefined in JavaScript. That’s why If you try to get their properties, it would raise a TypeError. As JavaScript internally wouldn’t be able to create a wrapper for accessing properties of these two objects.

Please while writing code in JavaScript to keep in mind that equality operator(==) would consider a value and it’s equivalent Wrapper object as same, but strict equality operator(===) may consider these as not same.

var a = "Computer Science Hub"; //String in JavaScript
var b = new String(a);   //Using new String() as constructor to make Wrapper Objects
a == b; (true) //Wrapper object and value are same
a === b; (false) //But these are not strictly same 

If you finds this useful and your learning JavaScript Programming Language then on this website I’ve put a lot of content about programming in JavaScript. You can check this out here – JavaScript Computer Science Hub.

Comments to: Wrapper Object in JavaScript

Your email address will not be published.