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:
let x = 10; x += 5; // 等效于 x = x + 5
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:
条件 ? 值1 : 值2
For example:
const isEven = n => (n % 2 === 0) ? true : false;
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:
myLabel: while (condition) { // ... }
4. Object literal
In object literals, colons are used to specify keys and values. For example:
const person = { name: "John Doe", age: 30 };
5. Spread operator (ES6)
In ES6, colon can be used with the spread operator (...) for expansion Array or object. For example:
const arr1 = [1, 2, 3]; const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
6. Type annotation (TypeScript)
In TypeScript, the colon is used to specify the type of a variable or function. For example:
let num: number = 10;
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!