Marcin Karkocha
Marcin Karkocha

Reputation: 41

Javascript: what's colon operator in variable name?

i have code like this:

var db: name = dbFunction(true);

dbFunction returning Object.

I have question, what doing this colon operator in variable name?

Upvotes: 0

Views: 2487

Answers (3)

James
James

Reputation: 5169

The colon has several uses in JavaScript.

  1. It's used to separate keys from values in the JSON notation.
var db = {
    name: dbFunction(name)
};
  1. It's the ternary operator:

var db = (1 == 1 ? true : false);

  1. Labels aka GOTO. Stay away from them.

Upvotes: 3

Thomas Gerot
Thomas Gerot

Reputation: 50

It is also used in switch cases:

switch(product) {
    case "apple":
        return "Yum";
        break;
    case "orange":
        return "juicy!";
        break;
    case "milk":
        return "cold!";
        break;
}

Upvotes: 0

Matt
Matt

Reputation: 75317

It's a high tech operator that guarantees a syntax error when used like that.

In it's normal use, you might see it used in object literal syntax to denote key:value pairs;

var object = {
    "name": "value",
    "name2": "value2"
}

It can also be used to define a label (less common).

loop1:  
for (var i=0;i<10; i++) {
   for (var j=0;j<10;j++) {
      break loop1; // breaks out the outer loop
   }  
}   

And it's part of the ternary operator;

var something = conditional ? valueIfTrue : valueIfFalse;

Upvotes: 5

Related Questions