Operators and Statements in ArkTS
Assignment Operators
- The simple assignment operator is =, used as x = y.
- Compound assignment operators combine assignment with other operations. For example, x op = y is equivalent to x = x op y. These include +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, |=, and ^=.
Comparison Operators
| Operator | Description |
|---|---|
| === | Returns true if the two operands are strictly equal. Operands of different types are considered unequal. |
| !== | Returns true if the two operands are strictly not equal. Operands of different types are considered unequal. |
| == | Returns true if the two operands are equal. |
| != | Returns true if the two operands are not equal. |
| > | Returns true if the left operand is greater than the right operand. |
| >= | Returns true if the left operand is greater than or equal to the right operand. |
| < | Returns true if the left operand is less than the right operand. |
| <= | Returns true if the left operand is less than or equal to the right operand. |
Arithmetic Operators
- Unary operators: -, +, --, ++.
- Binary operators:
| Operator | Description |
|---|---|
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| / | Division |
| % | Remainder after division |
Bitwise Operators
| Operator | Description |
|---|---|
| a & b | Bitwise AND: Sets a bit to 1 only if both corresponding bits of the operands are 1; otherwise, sets it to 0. |
| a | b |
| a ^ b | Bitwise XOR: Sets a bit to 1 if the corresponding bits of the operands are different; otherwise, sets it to 0. |
| ~ a | Bitwise NOT: Inverts the bits of the operand. |
| a << b | Left shift: Shifts the binary representation of a to the left by b bits. |
| a >> b | Arithmetic right shift: Shifts the binary representation of a to the right by b bits with sign extension. |
| a >>> b | Logical right shift: Shifts the binary representation of a to the right by b bits, filling with zeros on the left. |
Logical Operators
| Operator | Description |
|---|---|
| a && b | Logical AND |
| a | |
| ! a | Logical NOT |
If Statement
The if statement allows you to execute different statements based on a logical condition. When the condition is true, the corresponding set of statements is executed; otherwise, another set (if provided) is executed. The else part can also contain an if statement.
An if statement takes this form:
if (condition1) {
// Statement 1
} else if (condition2) {
// Statement 2
} else {
// Else statement
}
The conditional expression can be of any type. However, for non - boolean types, implicit type conversion will occur.
let s1 = 'Hello';
if (s1) {
console.log(s1); // Prints "Hello"
}
let s2 = 'World';
if (s2.length != 0) {
console.log(s2); // Prints "World"
}
Switch Statement
The switch statement executes a block of code that matches the value of a switch expression.
Here's the structure of a switch statement:
switch (expression) {
case label1: // If label1 matches, execute
// ...
// Statement 1
// ...
break; // Optional
case label2:
case label3: // If label2 or label3 matches, execute
// ...
// Statement 23
// ...
break; // Optional
default:
// Default statement
}
If the value of the switch expression equals a label's value, the corresponding statements are executed. If no label matches and a default clause is present, the code block associated with default is executed. The break statement (optional) allows you to exit the switch statement and continue executing statements after the switch. Without a break, the next label's code block will be executed.
Conditional Expressions
A conditional expression returns one of two expressions based on the boolean value of the first expression. The syntax is:
condition ? expression1 : expression2
If condition is truthy (a value that converts to true), expression1 is used as the result; otherwise, expression2 is used.
let message = Math.random() > 0.5 ? 'Valid' : 'Failed';
For Statement
A for statement repeatedly executes a block of code until the loop exit condition becomes false. Its structure is:
for ([init]; [condition]; [update]) {
statements
}
The execution flow of a for statement is as follows:
- Evaluate the init expression (if any), typically used to initialize one or more loop counters.
- Evaluate the condition. If it's truthy, execute the statements in the loop body. If it's falsy, the for loop terminates.
- Execute the statements in the loop body.
- If an update expression is present, evaluate it.
- Return to step 2.
Example:
let sum = 0;
for (let i = 0; i < 10; i += 2) {
sum += i;
}
For - of Statement
The for - of statement is used to iterate over arrays or strings. Here's an example:
for (forVar of expression) {
statements
}
Example:
for (let ch of 'a string object') {
/* Process ch */
}
While Statement
A while statement executes statements as long as the condition is truthy. Here's an example:
while (condition) {
statements
}
Example:
let n = 0;
let x = 0;
while (n < 3) {
n++;
x += n;
}
Do - while Statement
The statements will be repeatedly executed as long as the condition is truthy. Here's an example:
do {
statements
} while (condition)
Example:
let i = 0;
do {
i += 1;
} while (i < 10)
Break Statement
The break statement is used to terminate a loop or switch.
Example:
let x = 0;
while (true) {
x++;
if (x > 5) {
break;
}
}
If the break statement is followed by an identifier, control is transferred outside the statement block identified by that label.
Example:
let x = 1;
label: while (true) {
switch (x) {
case 1:
// statements
break label; // Break out of the while statement
}
}
Continue Statement
The continue statement stops the execution of the current loop iteration and passes control to the next iteration.
Example:
let sum = 0;
for (let x = 0; x < 100; x++) {
if (x % 2 == 0) {
continue;
}
sum += x;
}
Throw and Try Statements
The throw statement is used to throw exceptions or errors:
throw new Error('this error')
The try statement is used to catch and handle exceptions or errors:
try {
// Block of statements where exceptions may occur
} catch (e) {
// Exception handling
}
In the following example, throw and try statements are used to handle division - by - zero errors:
class ZeroDivisor extends Error {}
function divide(a: number, b: number): number {
if (b == 0) throw new ZeroDivisor();
return a / b;
}
function process(a: number, b: number) {
try {
let res = divide(a, b);
console.log('result: ' + res);
} catch (x) {
console.log('some error');
}
}
The finally statement is supported:
function processData(s: string) {
let error: Error | null = null;
try {
console.log('Data processed: ' + s);
// ...
// Statements where exceptions may occur
// ...
} catch (e) {
error = e as Error;
// ...
// Exception handling
// ...
} finally {
if (error != null) {
console.log(`Error caught: input='${s}', message='${error.message}'`);
}
}
}
Top comments (0)