0

Consider the following codes:

var str = "abc";
 str.foo = 123;  // write - ignored
123
 str.foo  // read
undefined

Why do I get undefined? Shouldn't that property output 123? What is the reason for it outputting undefined?

Since var str is a string, why don't properties show up a second time?

Cant we add properties and methods to a string?

0

1 Answer 1

0

You are defining str as a string, not an object. Maybe you meant to do something like this:

var o = {};
o.str = "abc";
o.foo = 123;

See the selected answer to this question for lots of great detail:

Why can't I add properties to a string object in javascript?

Sign up to request clarification or add additional context in comments.

3 Comments

str = new String("abc");
This question is on the way to being closed as a duplicate. see here meta.stackexchange.com/questions/82420/… for why you shouldn't answer these types of questions.
@frontendmagic I just deleted a comment questioning why you wrote that, but after a quick test, its quite clear. typeof new String("abc") is object whereas typeof "abc" is string. Thanks for the comment!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.