When to use ":"(colon) operator in javascript vs "=" operator?

Viewed 8331

I tried looking online everywhere for past hour, but I can't seem to figure out when to use colon operator : vs = operator in javascript? From what I can tell so far, it seems when defining object properties use colon :.

3 Answers

The JavaScript language was built by Brandon Eich using the = sign as an assignment operator. Back in 1995, most programming languages, like Basic, Turbo Pascal, Delphi, C, C++, etc... used the same method of assigning values to variables.

Rapidly creating new objects in JavaScript using colons : became popular because of Douglas Crockford's work in defining the JSON specification. JSON is easier-to-write & more compact than XML. The JSON.parse() method removes the need to build a client-side XML parser. As a result, JSON is also faster to code than XML. Thus JSON become popular as a data transfer format between servers & client browsers.

If you look at the http://www.json.org you can see how new objects can be written quickly using a {"key1": value1, "key2": value2} pair notation. The use of the colon : is simply shorthand notation for writing longhand object properties, which use the equal sign = as the operator.

Longhand JavaScript Example: (73 characters)

let myObject = new Object();
myObject.a = 1;
myObject.b = 2;
myObject.c = 3;

Shorthand JSON Example: (42 characters)

let myObject = {
  "a": 1,
  "b": 2,
  "c": 3
};

Minified examples:

let myObject=new Object();myObject.a=1;myObject.b=2;myObject.c=3; (65 characters)
let myObject={'a':1,'b':2,'c':3}; (33 characters with quotes, 27 characters without)

You can use equals = or colons : in your code. There isn't any rule, nor best practice about which one is preferred. They can be used together in the same line of code.

let myObject = {a:1, b:2, c:3};

Wikipedia adds more context about JSON, with their JSON page.

Related