What does ':' (colon) do in JavaScript?
Asked Answered
B

11

196

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 };
Beeves answered 7/1, 2009 at 0:52 Comment(0)
U
272
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';
Unerring answered 7/1, 2009 at 0:55 Comment(3)
So similar to C# object initializer syntax. Thanks!Beeves
What if there is no enclosing object?Antitragus
@FranciscI.B if i had to guess, i think that's TypeScript, which is a superset of JavaScript. It's declaring a class, with a var named xMin, whose type is a float. Pretty sur that's what that means.Loper
W
114

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++

}
Wireman answered 7/1, 2009 at 0:52 Comment(3)
A goto cannot be disguised: you simply break goto; and you've found it! ;)Raimund
MDN Reference page for JS Label: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Vincennes
yep, that's why a=>{b:2} will not throw and return undefinedThematic
W
82

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.

Wireman answered 7/1, 2009 at 1:13 Comment(4)
AKA "ternary operator". Note that the OP is strictly asking about the object literal case. If we're to go even beyond what the OP is asking, the colon is also used in labels.Tulle
yes I did mean that. I should just stay off the internet, really, if i'm going to go around flagrantly mis-identifying programming concepts like that.Wireman
It would be awesome to see it used for labels and whatever else so the use is never confused @AtesGoral because I am now still googling those right now.Annunciata
Maybe it would be easier to list the things that : isn't used for in Javascript.Aldarcy
C
50

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.

Campus answered 7/1, 2009 at 1:1 Comment(4)
As I read your response I thought I would vote it up, but then you said that "It is also known as JSON". Object literals and JSON are definitely not the same thing, indeed your examples before you mention JSON are not valid JSON.Baobaobab
@Baobaobab The difference between the 2 are very subtle, but important nonetheless. I've updated my answer to be more specific in regards to that.Campus
I see the update. Nice. Note that JSON requires that key names be in quotes.Baobaobab
Why do you have to mention all of that twice? When you said "and then use it like"Fate
R
19

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
Rockel answered 7/1, 2009 at 1:0 Comment(1)
Great because it gave me the term to search for and find out more information.Gordan
B
15

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";
Bean answered 8/4, 2016 at 15:28 Comment(1)
A single colon can also be used for short-circuit evaluation in lieu of ||. Example: var a = false, b = a || 'Default value'; is equivalent to var a = false, b = a : 'Default value';Makebelieve
U
14

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();
}
Upwards answered 8/6, 2012 at 8:0 Comment(0)
G
11

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

Genuine answered 7/6, 2011 at 10:57 Comment(0)
E
10

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.

Estebanesteem answered 15/11, 2018 at 12:48 Comment(2)
Wow! How do you even know this?Pyroxene
@Pyroxene I have seen some usages of it, I guess.Estebanesteem
D
8

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.

Dogleg answered 7/1, 2009 at 0:56 Comment(3)
JSON is only a subset of JavaScript object initialization syntax. '{ a: k() }' where k is a function is not JSON, but it is perfectly fine JavaScript object initialization syntax.Unerring
To be pedantic, no, it's not "JSON". It looks like JSON. It's the object literal syntax that is native to JavaScript and that can appear directly inside code. JSON on the other hand is a data serialization/interchange format. JSON is JSON only when it's "airborne", i.e. in transit or when it's not yet parsed into a real object.Tulle
+1 for Ates Goral, but note that the example given doesn't even look like JSON: the names would have to be in double-quotes for it to be valid JSON syntax.Ruffin
H
5

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.

Historical answered 9/6, 2016 at 19:6 Comment(2)
I came upon this, and fyi actually what is happening here is that you are using a label before your statement. No assignment is made, but the statement event.target.offsetLeft + event.target.clientWidth/2; does run each time your ondrag method is called, but never assign the value to nub0xBallot
Actually this is being used as an evaluation, and the : is being treated as though it were a ||. Therefore, event.target.offsetLeft + event.target.clientWidth/2; will only trigger each time provided nub0x equates to false.Makebelieve

© 2022 - 2024 — McMap. All rights reserved.