Home >Web Front-end >JS Tutorial >What does colon mean in js
The colon in JavaScript has six uses: 1. Assignment operator; 2. Conditional operator (ternary operator); 3. Label statement; 4. Object literal; 5. Extension operator ( ES6); 6. Type annotations (TypeScript).
The meaning of colon in JavaScript
In JavaScript, colon (:), as an operator, has multiple uses.
1. Assignment operator
The most common use of colon is as an assignment operator. It assigns the value of an expression to a variable. For example:
<code class="javascript">let x = 10; x += 5; // 等效于 x = x + 5</code>
2. Conditional operator (ternary operator)
The colon is also used as a conditional operator, also known as the ternary operator. It returns one of two values based on a conditional expression. The syntax is as follows:
<code class="javascript">条件 ? 值1 : 值2</code>
For example:
<code class="javascript">const isEven = n => (n % 2 === 0) ? true : false;</code>
3. Label statements
Colons can be used to add labels to statements. This allows jumping to the marked statement using the break
or continue
statement. For example:
<code class="javascript">myLabel: while (condition) { // ... }</code>
4. Object literal
In object literals, colons are used to specify keys and values. For example:
<code class="javascript">const person = { name: "John Doe", age: 30 };</code>
5. Spread operator (ES6)
In ES6, colon can be used with the spread operator (...) for expansion Array or object. For example:
<code class="javascript">const arr1 = [1, 2, 3]; const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]</code>
6. Type annotation (TypeScript)
In TypeScript, the colon is used to specify the type of a variable or function. For example:
<code class="typescript">let num: number = 10;</code>
The above is the detailed content of What does colon mean in js. For more information, please follow other related articles on the PHP Chinese website!