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
That is, numbers have methods.
The same is true for other programming languages like Ruby.
let a = "foo"
If we take the type of this variable it will be of type string:
console.log(typeof a) // "string"
How do we create string objects? Like this:
let b = new String(a) console.log(typeof b) // "object"
Thus, if we compare the values of
b we will get:
console.log(a == b) // true console.log(a === b) // false
As you know, the
== operator will compare for equality after doing any necessary type conversions. The
=== operator won't do any conversion. And as
b are of different types, then we get
We can also get primitives from
String calls in a non constructor context. That means, called without the
let c = String(a) console.log(typeof c) // "string" console.log(a == c) // true console.log(a === c) // true
As you see, this time the
=== operator returns
c are both primitives.
Certainly, we can do something like this:
console.log(a.length) // 3 console.log(a.toUpperCase()) // "FOO"
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.
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