What does ':' (colon) do in JavaScript?

Javascript

Javascript Problem Overview


I'm learning JavaScript and while browsing through the jQuery library I see : (colon) being used a lot. What is this used for in JavaScript?

// Return an array of filtered elements (r)
// and the modified expression string (t)
   return { r: r, t: t };

Javascript Solutions


Solution 1 - Javascript

var o = {
    r: 'some value',
    t: 'some other value'
};

is functionally equivalent to

var o = new Object();
o.r = 'some value';
o.t = 'some other value';

Solution 2 - Javascript

And also, a colon can be used to label a statement. for example

var i = 100, j = 100;
outerloop:
while(i>0) {
  while(j>0) {
   j++

   if(j>50) {
     break outerloop;
   }
  }
i++

}

Solution 3 - Javascript

You guys are forgetting that the colon is also used in the ternary operator (though I don't know if jquery uses it for this purpose).

the ternary operator is an expression form (expressions return a value) of an if/then statement. it's used like this:

var result = (condition) ? (value1) : (value2) ;

A ternary operator could also be used to produce side effects just like if/then, but this is profoundly bad practice.

Solution 4 - Javascript

The ':' is a delimiter for key value pairs basically. In your example it is a Javascript Object Literal notation.

In javascript, Objects are defined with the colon delimiting the identifier for the property, and its value so you can have the following:

return { 
    Property1 : 125,
    Property2 : "something",
    Method1 : function() { /* do nothing */ },
    array: [5, 3, 6, 7]
};

and then use it like:

var o =  { 
    property1 : 125,
    property2 : "something",
    method1 : function() { /* do nothing */ },
    array: [5, 3, 6, 7]
};

alert(o.property1); // Will display "125"

A subset of this is also known as JSON (Javascript Object Notation) which is useful in AJAX calls because it is compact and quick to parse in server-side languages and Javascript can easily de-serialize a JSON string into an object.

// The parenthesis '(' & ')' around the object are important here
var o = eval('(' + "{key: \"value\"}" + ')');

You can also put the key inside quotes if it contains some sort of special character or spaces, but I wouldn't recommend that because it just makes things harder to work with.

Keep in mind that JavaScript Object Literal Notation in the JavaScript language is different from the JSON standard for message passing. The main difference between the 2 is that functions and constructors are not part of the JSON standard, but are allowed in JS object literals.

Solution 5 - Javascript

It is part of the object literal syntax. The basic format is:

var obj = { field_name: "field value", other_field: 42 };

Then you can access these values with:

obj.field_name; // -> "field value"
obj["field_name"]; // -> "field value"

You can even have functions as values, basically giving you the methods of the object:

obj['func'] = function(a) { return 5 + a;};
obj.func(4);  // -> 9

Solution 6 - Javascript

It can be used to list objects in a variable. Also, it is used a little bit in the shorthand of an if sentence:

var something = {face: 'hello',man: 'hey',go: 'sup'};

And calling it like this

alert(something.man);

Also the if sentence:

function something() {  
  (some) ? doathing() : dostuff(); // if some = true doathing();, else dostuff();
}

Solution 7 - Javascript

These are generally the scenarios where colon ':' is used in JavaScript

1- Declaring and Initializing an Object

var Car = {model:"2015", color:"blue"}; //car object with model and color properties

2- Setting a Label (Not recommended since it results in complicated control structure and Spaghetti code)

List: 
while(counter < 50)
{
     userInput += userInput;
     counter++;
     if(userInput > 10000)
     {
          break List;
     }
}

3- In Switch Statement

switch (new Date().getDay()) {
    case 6:
        text = "Today is Saturday";
        break; 
    case 0:
        text = "Today is Sunday";
        break; 
    default: 
        text = "Looking forward to the Weekend";
}

4- In Ternary Operator

document.getElementById("demo").innerHTML = age>18? "True" : "False";

Solution 8 - Javascript

Let's not forget the switch statement, where colon is used after each "case".

Solution 9 - Javascript

That's JSON, or JavaScript Object Notation. It's a quick way of describing an object, or a hash map. The thing before the colon is the property name, and the thing after the colon is its value. So in this example, there's a property "r", whose value is whatever's in the variable r. Same for t.

Solution 10 - Javascript

Another usage of colon in JavaScript is to rename a variable, that is:

const person = { 
    nickNameThatIUseOnStackOverflow: "schlingel",
    age: 30,
    firstName: "John"
};
let { nickNameThatIUseOnStackOverflow: nick } = person; // I take nickNameThatIUseOnStackOverflow but want to refer it as "nick" from now on.
nick = "schling";

This is useful if you use a third party library that returns values having awkward / long variable names that you want to rename in your code.

Solution 11 - Javascript

One stupid mistake I did awhile ago that might help some people.

Keep in mind that if you are using ":" in an event like this, the value will not change

var ondrag = (function(event, ui) {
            ...

            nub0x: event.target.offsetLeft + event.target.clientWidth/2;
            nub0y = event.target.offsetTop + event.target.clientHeight/2;

            ...
        });

So "nub0x" will initialize with the first event that happens and will never change its value. But "nub0y" will change during the next events.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMicahView Question on Stackoverflow
Solution 1 - JavascriptyfeldblumView Answer on Stackoverflow
Solution 2 - JavascriptBretonView Answer on Stackoverflow
Solution 3 - JavascriptBretonView Answer on Stackoverflow
Solution 4 - JavascriptDan HerbertView Answer on Stackoverflow
Solution 5 - JavascriptbandiView Answer on Stackoverflow
Solution 6 - Javascriptuser1431627View Answer on Stackoverflow
Solution 7 - JavascriptLeo The FourView Answer on Stackoverflow
Solution 8 - JavascriptTeppo VuoriView Answer on Stackoverflow
Solution 9 - JavascriptJW.View Answer on Stackoverflow
Solution 10 - JavascriptschlingelView Answer on Stackoverflow
Solution 11 - JavascriptYounes NjView Answer on Stackoverflow