Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using colons in javascript variable names (eg. a:b:c)

Tags:

javascript

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?

like image 785
Jonathon Avatar asked Jan 09 '12 00:01

Jonathon


2 Answers

A colon in ECMAscript is there for three reasons

  • separating object keys from its values
  • inline conditional statements
  • labeling

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;
    }
}
like image 143
jAndy Avatar answered Oct 16 '22 02:10

jAndy


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.

like image 25
Jukka K. Korpela Avatar answered Oct 16 '22 02:10

Jukka K. Korpela