Alex Rivera | Logout

JavaScript variable and the same variable also be an object

Asked 2013-01-15T02:05:39.710
16

I am somewhat new to JavaScript and I have a question.

I know you can set variables and "sub-variables". Like:

var msg = "Hello World";
alert(msg);

and also

var msg = {
    lipsum: "Lorem Ipsum Dolor Sit Amet"
}
alert(msg.lipsum);

But I was wondering if you could do both, like

var msg = "Hello World" || {
    lipsum: "Lorem Ipsum"
}
alert(msg + msg.lipsum);

That way, you can declare a variable and also have the same variable be an object. Obviously it couldn't be done with what I did, but you get the picture.

Any help would be much appreciated!

Edit
Report

1 Answer

12

JavaScript variables can contain either objects or primitives. If you have an object, you can set properties on it (sub-variables), if you have a primitive, you can't.

Back to your example, JavaScript Strings can be either a primitive or an object, depending on how you define it, and to make matters more confusing, a primitive will be temporarily converted to an object when you try to access its properties.

The following code will display "bar", as our string is specifically declared as a String object with the new keyword:

a = new String("Hello World");
a.foo = "bar";
alert(a.foo);

If we remove the new String part, we get a primitive instead. JavaScript converts it for us when we try to set foo, but nothing gets saved, as it's really just a primitive underneath, and we get back the result "undefined" when we call alert(b.foo):

b = "Hello World";
b.foo = "bar";
alert(b.foo);

This is just one of many things that are confusing about the built-in JavaScript types, I recommend reading through the Mozilla Javascript Reference's Global Objects section for all the gory details.

answered 2013-01-15T02:24:44.527

Your Answer