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!
You have already learned that JavaScript variables are containers for data values. Objects are variables too.
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 .
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 .
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.
Actually, you can.
var msg = {
lipsum: "Lorem Ipsum",
toString: function() {return "Hello World!"}
};
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