DEV Community

Cover image for JavaScript Primitives have methods and properties! Wait what?
David Armendáriz
David Armendáriz

Posted on

JavaScript Primitives have methods and properties! Wait what?

Hey guys! How are you?

Last time, I was discussing with a colleague that everything in Python was an object. Even numbers. To show this, I just did the following:

print((2).__add__(2)) # should print 4
Enter fullscreen mode Exit fullscreen mode

That is, numbers have methods.
The same is true for other programming languages like Ruby.
However, in basically every other programming language (including JavaScript) we do have primitives. How do we create them? Well, with single or double quotes, like this:

let a = "foo"
Enter fullscreen mode Exit fullscreen mode

If we take the type of this variable it will be of type string:

console.log(typeof a) // "string"
Enter fullscreen mode Exit fullscreen mode

How do we create string objects? Like this:

let b = new String(a)
console.log(typeof b) // "object"
Enter fullscreen mode Exit fullscreen mode

Thus, if we compare the values of a and b we will get:

console.log(a == b) // true
console.log(a === b) // false
Enter fullscreen mode Exit fullscreen mode

As you know, the == operator will compare for equality after doing any necessary type conversions. The === operator won't do any conversion. And as a and b are of different types, then we get false.

We can also get primitives from String calls in a non constructor context. That means, called without the new keyword).

let c = String(a)
console.log(typeof c) // "string"
console.log(a == c) // true
console.log(a === c) // true
Enter fullscreen mode Exit fullscreen mode

As you see, this time the === operator returns true because a and c are both primitives.

But then, why we can call methods of primitives?

Certainly, we can do something like this:

console.log(a.length) // 3
console.log(a.toUpperCase()) // "FOO"
Enter fullscreen mode Exit fullscreen mode

We can get the length property of a primitive and call a toUpperCase method. Wait what? How can a primitive have properties and methods?

Well, they don't. It depends on the context.

When a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

The same happens with the other primitives in JavaScript:

  • Number
  • BigInt
  • Boolean
  • Symbol

To get the primitive value from these objects, just call the valueOf() method. For example:

let d = b.valueOf()
console.log(a == d) // true
console.log(a === d) // true
Enter fullscreen mode Exit fullscreen mode

Pretty cool!

Top comments (1)

Collapse
 
fullrx profile image
Dmitry Maltsev

Congratulations. JavaScript of the brains to be continued NaN times.