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 :
.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Do the Java Integer and Double objects have unnece
- Keeping track of variable instances
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)
Shorthand JSON Example: (42 characters)
Minified examples:
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.Wikipedia adds more context about JSON, with their JSON page.
The colon(:) operator as you correctly stated, is used to define an object property:
The equals(=) operator is used to assign values to something, a variable, an array etc.
If you only defined your object as:
You could assign properties to it like this:
When you are defining an object, you can use the
:
notation for defining values of properties.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.Or