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?

adamdehaven
  • 5,890
  • 10
  • 61
  • 84
Maizere Pathak.Nepal
  • 2,383
  • 3
  • 27
  • 41

1 Answers1

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?

Community
  • 1
  • 1
lbstr
  • 2,822
  • 18
  • 29
  • 2
    str = new String("abc"); – dyurkavets Apr 02 '13 at 15:43
  • This question is on the way to being closed as a duplicate. see here http://meta.stackexchange.com/questions/82420/remove-rep-gained-from-answering-a-question-that-is-a-duplicate for why you shouldn't answer these types of questions. – Ryan Apr 02 '13 at 15:52
  • @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! – lbstr Apr 02 '13 at 16:05