I have just noticed that I can do the following in javascript...
a:b:c:d = "happy days";
a:b:c = function(text){alert(text);};
I cannot however do...
var a:b:c:d = "happy days";
// or
var myObj = {prop:a:b:c:d};
I was not expecting this syntax to work under any circumstances. Does anyone have any idea what is going on when I successfully use the 'a:b=x' notation?
A colon in ECMAscript is there for three reasons
you discoverd the latter. What you are basically doing is creating a label called a
, then b
, then c
and finally you are assigning a value to a global variable d
. So after
a:b:c:d = "happy days";
console.log(a); // reference error
console.log(d); // "happy days";
Most common usage for this is within a switch
statement where we do it like
switch( foo ) {
case 0: break;
case 1: break;
// etc
}
But you can also directly "target" a label with the continue
statement. That comes very close to goto
in many other languages and looks like
foobar:
for(var i = 0; i < 10; i++) {
for(var j = 0; j < 10; j++) {
if( j === 2 )
continue foobar;
}
}
Quoting the ECMAScript standard: “A Statement may be prefixed by a label. Labelled statements are only used in conjunction with labelled break
and continue
statements.” A label consists of an identifier and a colon. So a:b:c:d = "happy days";
is just an assignment statement d = "happy days";
prefixed by three labels, which have no effect as such.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With