1

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?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
TrickOrTreat
  • 821
  • 1
  • 9
  • 23

2 Answers2

5

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • i don't think so that's a valid statement that i am looking for. We got confused simply because we have never used. This i have never used before, may be it can be beneficial in some way, only that i want to know, not that its confusing or something cz i get that obviously :) – TrickOrTreat Jul 13 '19 at 17:48
0

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);
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103