Flezcano
Flezcano

Reputation: 1687

What the heck operator ":" is for?

If you put on the console smth like a: "Hi" it does not show any error but it prints the value. But when you put a , it says that the variable does not exist. So, why is that? I know colons are used for defining properties inside a json object, but why is that example does not throw an error from the begging.

EDIT : I am looking for the use of colons out of a json object. Not in a switch statement either.

Upvotes: 3

Views: 200

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85012

That is a label. They can be used with continue and break when doing nested loops or nested switches, but you'll almost never run into them. Due to their rarity they may cause confusion, and so i'd generally recommend against using them unless you have a compelling reason to do so.

outer:
for (var i = 0; i < 10; i++) {
   inner:
   for (var j = 0; j < 10; j++) {
      console.log(i, j)
      if (j == 2) {
         break outer;
      }
   }
}

Upvotes: 11

Related Questions