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

牧云@^-^@ 提交于 2019-12-01 06:02:44

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.

The colon(:) operator as you correctly stated, is used to define an object property:

var object = {
  property:value
}

The equals(=) operator is used to assign values to something, a variable, an array etc.

If you only defined your object as:

var object = {}

You could assign properties to it like this:

object.property = value;
quirimmo

When you are defining an object, you can use the : notation for defining values of properties.

var obj = { test: "value" };

The = operator is used for defining variable values. As in the above example the variable obj is equal to that object.

Pay attention that you can define object properties also using the = operator.

var obj = {};
obj.test = "value";

Or

obj["test"] = "value";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!