Built-in Function constructors

A string primitive is a string literal like so:

However, we can also create String objects like so:

This ‘a’ string, not a primitive. It was created using object String. Thus, when you
display it, you’ll see that it has many properties 0, 1, 2, with their values as 0: “B”, 1: “o”, 2: “b”.

Its length is 3.


StringĀ {"Bob"}
0: "B"
1: "o"
2: "b"
length: 3
__proto__: String[[PrimitiveValue]]: "Bob"

When you’re using function constructors to create Strings, Numbers, etc, you are creating Objects.

Add features to all String objects

if we invoke a function on a string literal, JS converts the string literal to a String object automatically:

However, we can’t do this for Number objects.

Danger

For example when we use value comparison ‘==’ between primitive 3 and Number object 3, it will compare the values 3, and give you true

However, === compares values AND types. So in this case, it would give us false

Array object dangers

Because for Array objects, the indexes (0, 1, 2, …n) become properties of the Array Object. Their values would be the data in the array.

However, this presents a problem. When we use for-in to loop through arrays, it goes like this:

print out prop, and you’ll get string type index “0”, “1”, “2”…etc. These are properties of our Array object.

However, if we were to add properties to Array prototype, it would also show.

if you were to use the for..in loop again, you’ll see the property:


ricky
joy
En En
hahah

In order to combat this, we can use hasOwnProperty. First we have to check to see if the array’s string type indexes are its own property.

We see that it is. Our haha propety belongs to the prototype object, and not of the array object itself:

Thus, when using for..in, you’ll have to add a check to display if the property is the object’s own.

…or you can also simply use the original for loop like so