Skip to content Skip to sidebar Skip to footer

How : Operator Works In Javascript

Why next code doesn't occur errors? var bar = 1, foo = {}; foo: { bar: 2; baz: ++bar; }; It returns 2 It known that javascript has labels, it helps to manage loops an

Solution 1:

It's not an error because the foo in foo: {...} is a statement label. It has nothing to do with your foo variable, and it has nothing to do with assigning anything to anything.

Similarly, the { and } define a block, not an object, and the bar and baz inside are also statement labels.

The statements

2;

and

++bar;

are perfectly valid. The first looks a bit odd, but it's valid; in JavaScript, any expression can be used as a statement, including a simple constant. (Which is useful; it's how JavaScript slipped in the "use strict" directive.)

The result is 2 because the block takes the value of the last statement in the block, which is ++bar;.

Unless something is using those statement labels, that code is equivalent to:

var bar = 1,
    foo = {};

2;
++bar;

Could this code be useful?

Purely as given, I don't see how, no. But note that if you had a loop inside the foo block, and you had something after the loop, you could use a directed break to jump past the thing after the loop:

var bar = 1,
  foo = {};

foo: {
  bar: 2;
  baz: ++bar;
  for (var n = 0; n < 10; ++n) {
    snippet.log("n = " + n);
    if (Math.random() < 0.3) {
      break foo;
    }
  }
  snippet.log("Probably don't get here");
};
snippet.log("Done");
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --><scriptsrc="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

There, you won't see Probably don't get here except in the outlying case where Math.random() returned a value less than 0.3 ten times in a row.

You need a loop or a switch in order to do that, though; break is only valid in loops and switch. And it would be a very unusual thing to do...

Post a Comment for "How : Operator Works In Javascript"