Code like this:
var str = "Hello StackOverflow !";
alert(typeof str);
gives me string
as result. This means strings are not objects, then why do we have properties of a string str
like str.substring
, str.indexOf etc.?
Also when i set property to it as
str.property = "custom property is set";
and trying to get this alert(str.property)
, it gives me undefined
. Why?
A string like "Hello" is not an object in JavaScript, but when used in an expression like
"Hello".indexOf(2)
A new object derived from the constructor function String
is produced wrapping the string "Hello"
. And indexOf
is a property of String.prototype
so things work as expected, even though there is a lot of magic going on.
In the following case
> var s = "xyz"; s.prop = 1; console.log(s.prop);
undefined
The reason you see undefined
is that:
s
is given a value which is a primitive strings.prop = 1
and property named prop
is assigned to a new, anonymous wrapper object.s
. That is not the same wrapper object as in the second statement, and it does not have a prop
property, so undefined
is produced when asking for its value according to the basic JavaScript rules.This depends on how you defines object and what are you referring to when you say string. When you use the word string, you can be referring to just the primitive, or the wrapper object.
In JavaScript there are 5 primitive types: undefined, null, boolean, string and number. Everything else is an object.
Unlike objects, primitives don't really have properties. They exist as values. This explains why you cannot assign a property to a string:
var archy = "hello";
archy.say = "hello";
console.log(archy.say); // undefined
But sometimes manipulating a primitive would make one feel as if she/he is manipulating an object because primitives appear to have methods.
var archy = "hello";
console.log(archy.length); //5
This is due to the fact that JavaScript creates a wrapper object when you attempt to access any property of a primitive.
Here is an extract from Javascript: The Definitive Guide
The temporary objects created when you access a property of a string, number, or boolean are known as wrapper objects, and it may occasionally be necessary to distinguish a string value from a String object or a number or boolean value from a Number or Boolean object. Usually, however, wrapper objects can be considered an implementation detail and you don’t have to think about them. You just need to know that string, number, and boolean values differ from objects in that their properties are read-only and that you can’t define new properties on them.
Strings are pure objects: http://www.ecma-international.org/ecma-262/5.1/#sec-15.5
So the question is, what does the typeof
operator. It simply acts according to its ECMA specification:
http://www.ecma-international.org/ecma-262/5.1/#sec-11.4.3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With