October 30, 2023
Using colon in object literals
The colon is primarily used within an object literal to separate property names (keys) from their corresponding values.
Syntax for object literals
Here's how a colon is used in an object literal:
In the example above,
age are properties of the
person object, while 'Alice' and 30 are their respective values, with each pair being separated by a colon.
Colons are also used in nested objects to maintain the key-value relationship at every level.
Methods in objects
Methods in objects are defined with the colon separating the method name from its function definition.
Computed property names
With computed property names, the colon separates the dynamically evaluated property name from its value.
Using colon in ternary operators
The colon also plays a crucial role in the ternary operator (or conditional operator), which is a shorthand for an
Syntax for ternary operators
Here's an example of a ternary operator in action:
Nesting ternary operators
Ternary operators can be nested, and the colon plays its role in demarcating the alternatives at each level of the condition.
Standalone ternary operation
Ternary operators can also be used without an assignment.
As a function argument
Ternary operators can be passed as arguments to functions.
Using colon in labeled statements
Syntax for labeled statements
An example of a labeled loop is as follows:
Breaking and continuing with labels
Labels can be used with
continue to proceed to the next iteration of the labeled loop.
Block statements with labels
Labels can also be applied to block statements.
Using colon in switch statements
switch statements, the colon follows case clauses, providing a clear demarcation of the case value and its associated block of code.
Syntax for switch statements
Summary of uses
- Object literals to pair keys with values, define methods, and with computed property names.
- Ternary operators to separate the two possible outcomes of a condition, which can be used standalone or as function arguments.
- Labeled statements to distinguish the label from the associated statement, and in switch cases to separate the case value from its execution block.
How to Truncate Date in MySQL