Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How : operator works in Javascript

Tags:

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 and if-statements. Could this code be useful? I saw that AngularJS framework with :: operator provide one-time binding. Maybe do you hear some another example of using that strange operator.

like image 507
Oleksii Avatar asked Aug 22 '26 22:08

Oleksii


1 Answers

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 -->
<script src="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...

like image 126
T.J. Crowder Avatar answered Aug 24 '26 11:08

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!