During question solving, I came across a code problem:
var a = {};
a: {m: "something"; n: "another thing";}
Now if I want to access m
or n
here, how am I suppose to?
And where can this kind of code be used in practice?
During question solving, I came across a code problem:
var a = {};
a: {m: "something"; n: "another thing";}
Now if I want to access m
or n
here, how am I suppose to?
And where can this kind of code be used in practice?
The code posted is not useful; it does not actually do anything. It's probably designed as a trick question.
var a = {};
a: {m: "something"; n: "another thing";}
In that code, a:
is a label, and the { }
block following it is a block of statements. That block also contains labeled statements, m
and n
. Thus the code is equivalent to
var a = {};
{
"something";
"another thing";
}
You can prove this to yourself by adding more statements to the block
var a = {};
a: {m: "something"; n: "another thing"; console.log("in the block!"); }
Any statement in JavaScript can have a label, but labels are only useful in conjunction with the break
and continue
statements. Labels should therefore only be used with looping statements like for
and while
.
JavaScript has the concept of label
statements. It allows us to name loops and blocks in JavaScript. We can then use these labels to refer back to the code later while using break
or continue
. Hence, we can only use labels with break and continue.
foo: {
console.log('face');
break foo;
console.log('this will not be executed');
}
console.log('swap');
// this will log:
// "face"
// "swap
If it is not about label statement because your posted code is not useful for this concept, then you can remove extra ;
add comma ,
and finally get value of m
var a = {};
a = {
m: "something",
n: "another thing"
};
console.log(a.m);