Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript variable and the same variable also be an object

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!

like image 768
ModernDesigner Avatar asked Jan 15 '13 02:01

ModernDesigner


People also ask

Is a variable an object in JavaScript?

You have already learned that JavaScript variables are containers for data values. Objects are variables too.

Can I use variable as object key JavaScript?

Use Variable as Key for Objects in JavaScript log(obj. key); console. log(obj["key"]); The variable varr was set as the key for the object obj .

How do you make a variable equal another variable?

After a value is assigned to a variable using the assignment operator, you can assign the value of that variable to another variable using the assignment operator. var myVar; myVar = 5; var myNum; myNum = myVar; The above declares a myVar variable with no value, then assigns it the value 5 .

Can you have two variables with the same name JavaScript?

It's not possible, an if statement has no special scope, so you can't have two variables with the same name within the same scope and access both, the latter will overwrite the former, so they should have different names.


1 Answers

Actually, you can.

var msg = {
    lipsum: "Lorem Ipsum",
    toString: function() {return "Hello World!"}
};
like image 134
Niet the Dark Absol Avatar answered Oct 22 '22 01:10

Niet the Dark Absol