How: operator works in Javascript

Why doesn't the following code throw errors?

var bar = 1,
    foo = {};

foo: {
    bar: 2;
    baz: ++bar;
};

      

It returns 2

Javascript is known to have labels, it helps to manage loops and if-statements. Could this code be helpful? I've seen that the AngularJS framework with operator ::

provides a one-time binding. Maybe you hear another example of this strange operator being used.

+3


source to share


1 answer


This is not an error, because foo

in foo: {...}

is an operator shortcut . It has nothing to do with your variable foo

and has nothing to do with assigning anything to anything.

Similarly, {

and }

define a block, not an object, and inside bar

and baz

- also operator labels.

Assertions

2;

      

and

++bar;

      

are perfectly correct. The first one looks a little odd, but it is valid; in JavaScript, any expression can be used as a statement , including a simple constant. (Which is useful since JavaScript fits in the directive "use strict"

.)

Result 2

because the block takes on the value of the last statement in the block , which is ++bar;

.



If something doesn't use these statement labels, this code is equivalent to:

var bar = 1,
    foo = {};

2;
++bar;

      

Could this code be helpful?

Purely as stated, I don't see how, no. But keep in mind that if you had a loop inside a block foo

and had something after the loop, you could use directed break to slip past things 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>
      

Run code


You won't see it there Probably don't get here

, except when it Math.random()

returned a value less than 0.3

ten times in a row.

For this you need a loop or switch

; break

acts only in cycles andswitch

. And it will be an unusual thing...

+6


source







All Articles