目录

Basic Operators

ArkTS provides a rich set of operators for data operations, logical judgment, and assignment operations. Compound assignment and logical assignment operators, as well as operator precedence and associativity, are covered in Advanced Operators.

Assignment Operators

The assignment operator (=) assigns the value on the right to the variable on the left.

[h2]Simple Assignment (=)

Use = to assign the value on the right to the variable on the left. For object types, assignment follows reference semantics: the old and new variables point to the same object, and modifying one affects the other. Assignment of primitive types (such as number, boolean, and string) follows value semantics.

let value: number = 10;
let name: string = 'Alice';
let active: boolean = true;

// Reassign the value.
value = 20;
name = 'Bob';

An assignment expression returns the assigned value. Chained assignment such as a = b = 10 is syntactically supported, but it is not recommended. Assign values separately to improve readability.

let a: number;
let b: number;

// Counterexample: chained assignment
a = b = 10;

// Recommended: assign separately
a = 10;
b = 10;

[h2]Object Assignment

Assigning an object to a variable passes a reference rather than a copy—the new and old variables point to the same object, and modifying a property of one affects the other. To obtain an independent copy, you must implement a deep copy manually.

class Point {
  public x: number = 0;
  public y: number = 0;
}

let point: Point = new Point();
point.x = 10;       // Property assignment
point.y = 20;

let another: Point = point;  // Reference assignment
another.x = 30;    // point.x also becomes 30

Arithmetic Operators

Arithmetic operators include addition (+), subtraction (-), multiplication (*), division (/), remainder (%), and increment/decrement (++/--).

[h2]Addition Operator (+)

The addition operator performs numeric addition or string concatenation and returns the sum or concatenation result.

let addA: number = 10;
let addB: number = 5;

let sum: number = addA + addB;    // 15

// String concatenation
let greeting: string = 'Hello' + ' World';
let message: string = 'Count: ' + 10;

[h2]Subtraction Operator (-)

The subtraction operator (-) calculates the difference between two numeric operands, which must be of type number. Unlike +, which supports string concatenation, -, *, /, %, and unary negation do not allow cross-type operations involving types such as number and string.

let numberA: number = 10;
let numberB: number = 5;

let diff: number = numberA - numberB;   // 5
let negative: number = -10; // Represent a negative number.

[h2]Multiplication Operator (*)

The multiplication operator (*) computes the product of two numeric operands. The operands must be of the number type. ArkTS does not support string repetition (such as 'ab' * 3 in Python); use the repeat() method for string repetition.

let mulA: number = 10;
let mulB: number = 5;

let product: number = mulA * mulB;  // 50

// Calculate the area.
let width: number = 5;
let height: number = 10;
let area: number = width * height;  // 50

[h2]Division Operator (/)

The division operator (/) calculates the quotient of two numbers, and the result is always a floating-point number.

let divA: number = 10;
let divB: number = 4;

let quotient: number = divA / divB;  // 2.5

// Integer division.
let intDivision: number = Math.floor(10 / 4);  // 2

// Division by zero.
let zeroDiv: number = 10 / 0;   // Infinity
let negZeroDiv: number = -10 / 0;  // -Infinity
let zeroByZero: number = 0 / 0;  // NaN

[h2]Remainder Operator (%)

The remainder operator returns the remainder of a division and is used for loops and periodic calculations.

let modA: number = 10;
let modB: number = 3;

let remainder: number = modA % modB;  // 1

// Determine whether the number is even or odd.
let isEven: boolean = (modA % 2) === 0;
let isOdd: boolean = (modA % 2) !== 0;

[h2]Unary Negation Operator (-)

The unary negation operator (-) negates a numeric value, turning a positive value into a negative one and vice versa.

let negA: number = 5;
let negNegative: number = -negA;  // -5

let negB: number = -10;
let positive: number = -negB;  // 10

[h2]Exponentiation Operator (**)

The exponentiation operator calculates a power and returns the base raised to the power of the exponent.

let base: number = 2;
let exponent: number = 3;

let power: number = base ** exponent;  // 8 (2^3)

let square: number = 5 ** 2;   // 25
let cube: number = 3 ** 3;     // 27

Comparison Operators

Comparison operators determine the relationship between values and return a Boolean result.

[h2]Equality Operator (===)

Strict equality (===) returns true when both values and types are the same.

// Numeric comparison
let eqA: number = 5;
let eqB: number = 5;
console.info(`${eqA === eqB}`);     // true

// Different values
let eqNum1: number = 5;
let eqNum2: number = 10;
console.info(`${eqNum1 === eqNum2}`); // false

// Compare object references
class EqPoint {
  public x: number;
  public y: number;
  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }
}

let p1: EqPoint = new EqPoint(1, 2);
let p2: EqPoint = new EqPoint(1, 2);
console.info(`${p1 === p2}`);  // false (different objects)

// NaN is not equal to itself.
let nan1: number = 0 / 0;  // Floating-point calculation produces NaN.
let nan2: number = 0 / 0;  // Floating-point calculation produces NaN.
console.info(`${nan1 === nan2}`);        // false
console.info(`${Number.isNaN(nan1)}`);   // true

NaN is not equal to any value, including itself. NaN === NaN is always false, so do not use === to check whether a floating-point calculation produces NaN. Use Number.isNaN instead.

ArkTS also supports loose equality (==). Because static type checking limits comparisons between values of different types, the main difference between == and === is how they handle null and undefined: == considers them equal, whereas === distinguishes them. Unless specifically needed, use the stricter ===:

// == considers null and undefined equal.
let inputValue: string | null = null;
let missing: string | undefined = undefined;

console.info(`${inputValue == null}`);     // true
console.info(`${missing == null}`);        // true (undefined == null is true)
console.info(`${inputValue == missing}`);  // true

// === distinguishes null from undefined.
console.info(`${inputValue === null}`);  // true
console.info(`${missing === null}`);     // false (undefined !== null)

Use strict equality:

let eqValue: string | null = null;
let eqCount: number = 0;
// Recommended: use strict equality.
if (eqValue === null) { }
if (eqCount === 0) { }

[h2]Not Equal Operator (!==)

Strict inequality (!==) returns true when values or types differ. Loose inequality (!=) is likewise not recommended. Use !== consistently.

let neA: number = 5;
let neB: number = 3;
console.info(`${neA !== neB}`);     // true

let neNum1: number = 5;
let neNum2: number = 10;
console.info(`${neNum1 !== neNum2}`); // true

[h2]Greater Than Operator (>)

Greater than (>) returns true when the left-hand value is greater than the right-hand value.

let gtA: number = 10;
let gtB: number = 5;

console.info(`${gtA > gtB}`);     // true
console.info(`${gtB > gtA}`);     // false
console.info(`${gtA > gtA}`);     // false

// Compare strings by Unicode code points.
console.info(`${'b' > 'a'}`);     // true
console.info(`${'abc' > 'abb'}`); // true

[h2]Less-Than Operator (<)

Less than (<) returns true when the left-hand value is less than the right-hand value.

let ltA: number = 10;
let ltB: number = 5;

console.info(`${ltA < ltB}`);   // false
console.info(`${ltB < ltA}`);   // true
console.info(`${ltA < ltA}`);   // false

[h2]Greater Than or Equal To Operator (>=)

Greater than or equal to (>=) returns true when the left-hand value is greater than or equal to the right-hand value.

let gteA: number = 10;
let gteB: number = 5;
let gteC: number = 10;

console.info(`${gteA >= gteB}`);  // true
console.info(`${gteA >= gteC}`);  // true
console.info(`${gteB >= gteA}`);  // false

[h2]Less Than or Equal To Operator (<=)

Less than or equal to (<=) returns true when the left-hand value is less than or equal to the right-hand value.

let lteA: number = 10;
let lteB: number = 5;
let lteC: number = 10;

console.info(`${lteA <= lteB}`);  // false
console.info(`${lteA <= lteC}`);  // true
console.info(`${lteB <= lteA}`);  // true

Ternary Conditional Operator

The ternary conditional operator selects one of two values based on the Boolean value of a condition. It is a concise form of if-else, suitable for simple conditional assignments.

condition ? true value : false value
let age: number = 20;
let status: string = age >= 18 ? 'adult' : 'minor';

let score: number = 85;
let result: string = score >= 60 ? 'pass' : 'fail';

// Nested ternary operator
let grade: string =
  score >= 90 ? 'A' :
  score >= 80 ? 'B' :
  score >= 70 ? 'C' :
  score >= 60 ? 'D' : 'F';

// Function return
function getStatus(code: number): string {
  return code === 200 ? 'OK' : 'Error';
}

// Conditional assignment
let isAdmin: boolean = true;
let role: string = isAdmin ? 'admin' : 'user';

Nullish Coalescing Operator

The nullish coalescing operator (??) provides a default value, returning the right-hand value only when the left-hand value is null or undefined.

?? and logical OR || differ in how they handle falsy values: || returns the right-hand value whenever the left-hand value is falsy, potentially replacing valid values such as 0, '', and false. ?? returns the right-hand value only for null or undefined (a subset of falsy values), preserving other valid values.

let coalesceValue: string | null = null;
let coalesceResult: string = coalesceValue ?? 'default';
console.info(`${coalesceResult}`);  // 'default'

let value2: string = 'hello';
let result2: string = value2 ?? 'default';  // "hello"

// Difference from ||
let count: number = 0;
let text: string = '';
let flag: boolean = false;

// || replaces falsy values
let withOr1: number = count || 10;     // 10 (0 is falsy)
let withOr2: string = text || 'default'; // 'default'

// ?? replaces only null/undefined
let withNullCoalesce1: number = count ?? 10;      // 0 (0 is retained)
let withNullCoalesce2: string = text ?? 'default'; // '' (empty string is retained)

// Chained nullish coalescing
let primary: string | null = null;
let secondary: string | null = null;
let fallback: string = 'default';

let result3: string = primary ?? secondary ?? fallback;
console.info(`${result3}`);  // 'default'

Logical Operators

Logical operators include NOT (!), AND (&&), and OR (||). They perform logical operations on Boolean values and support short-circuit evaluation.

[h2]Logical NOT Operator (!)

Logical NOT (!) converts true to false and false to true.

let isA: boolean = true;
let isB: boolean = false;

console.info(`${!isA}`);  // false
console.info(`${!isB}`);  // true

// Convert double negation to a Boolean value.
let notValue: number = 5;
console.info(`${!!notValue}`);  // true (equivalent to Boolean(notValue))

[h2]Logical AND Operator (&&)

Logical AND (&&) returns true only when both operands are true. If the left-hand operand is false, evaluation short-circuits and skips the right-hand operand.

let andA: boolean = true;
let andB: boolean = true;
let andC: boolean = false;

console.info(`${andA && andB}`);  // true
console.info(`${andA && andC}`);  // false

// Truth table
// true && true   → true
// true && false  → false
// false && true  → false
// false && false → false

// Condition check
let andAge: number = 25;
let hasLicense: boolean = true;
let hasInsurance: boolean = true;

let canDrive: boolean = andAge >= 18 && hasLicense && hasInsurance;

[h2]Logical OR Operator (||)

Logical OR (||) returns true when either operand is true. If the left-hand operand is true, evaluation short-circuits and skips the right-hand operand.

let orA: boolean = true;
let orB: boolean = false;
let orC: boolean = false;

console.info(`${orA || orB}`);  // true
console.info(`${orB || orC}`);  // false

// Truth table
// true || true   → true
// true || false  → true
// false || true  → true
// false || false → false

// Either condition is met.
let orRole: string = 'admin';
let hasPermission: boolean = true;

let canAccess: boolean = orRole === 'admin' || hasPermission;

[h2]Short-Circuit Evaluation

The logical AND (&&) and logical OR (||) operators skip the evaluation of the right-hand side when the left-hand side already determines the result.

// && short-circuit: the right side is not executed when the left side is false.
function expensiveCheck(): boolean {
  console.info('Performing complex check');
  return true;
}

let enabled: boolean = false;
let circuitResult: boolean = enabled && expensiveCheck();  // expensiveCheck is not executed.

// || short-circuit: if the left side is true, the right side is not evaluated.
function fallbackValue(): string {
  console.info('Use the default value.');
  return 'default';
}

let circuitPrimary: string = 'primary';
let circuitValue: string = circuitPrimary || fallbackValue();  // "primary"; fallbackValue is not called.

// ?? short-circuit: if the left side is not null/undefined, the right side is not evaluated.
function expensiveDefault(): string {
  console.info('Perform the expensive default value calculation.');
  return 'default';
}

let provided: string | null = 'text';
let circuitResult2: string = provided ?? expensiveDefault();  // expensiveDefault is not executed.

Increment and Decrement Operators

The increment (++) and decrement (--) operators add 1 to or subtract 1 from a numeric value. The prefix form changes the value before use, while the postfix form uses the value before changing it.

let decrCount: number = 5;

// Pre-increment: increment first, then use.
let preInc: number = ++decrCount;  // decrCount=6, preInc=6

// Post-increment: use first, then increment.
let postInc: number = decrCount++; // decrCount=7, postInc=6

// Pre-decrement
let preDec: number = --decrCount;  // decrCount=6, preDec=6

// Postfix decrement.
let postDec: number = decrCount--; // decrCount=5, postDec=6

Optional Chaining Operator

The optional chaining operator (?.) safely accesses a variable or its properties that may be null/undefined, avoiding runtime errors.

// Access works whether the variable is an array or null.
function printScores(scores: number[] | null) {
  // Safely access a property: return undefined if scores is null.
  let scoreCount: number | undefined = scores?.length;
  console.info(`Score count: ${scoreCount}`);
  
  // Safely call a method: return undefined if scores is null.
  let hasPass: boolean | undefined = scores?.includes(60);
  console.info(`Has passing score: ${hasPass}`);
  
  // Combine with nullish coalescing to provide a default.
  let safeCount: number = scores?.length ?? 0;
  console.info(`Safe count: ${safeCount}`);
}

// Test the null case.
printScores(null);  // Output: Score count: undefined, Has passing score: undefined, Safe count: 0

// Test the array case.
printScores([80, 95]);  // Output: Score count: 2, Has passing score: false, Safe count: 2

Besides optional chaining, you can explicitly check for nullish values before using a value. After the check passes, the compiler narrows the value to a non-nullish type, allowing direct access within the branch. For optional properties nested at multiple levels, use optional chaining to access each level safely without repeated null checks:

interface NullableSub {
  sub?: string;
}

interface NullableObj {
  prop?: NullableSub;
}

let optionalValue: string | null = 'hello';

// Explicitly handle nullish values.
if (optionalValue !== null) {
  console.info(`${optionalValue.length}`);
}

// Use optional chaining.
let obj: NullableObj = {};
let sub: string | undefined = obj?.prop?.sub;
if (sub !== undefined) {
  console.info(`${sub}`);
}

Non-Null Assertion Operator

The non-null assertion operator (!) follows a nullable value and tells the compiler that the value is neither null nor undefined, allowing direct property access or method calls. Unlike optional chaining ?., which safely returns undefined for a nullish value, ! assumes the value is non-null and causes a runtime exception if it is actually nullish. Use it only when non-nullness is guaranteed; otherwise, prefer ?. or ??.

function getValue(): string | null {
  return 'Alice';
}

let nickname: string | null = getValue();
console.info(nickname!.toUpperCase());  // 'ALICE' (call directly after asserting non-nullness)