Kaya Operators Reference

Every operator, with precedence and behavior

Overview

Operators combine values and variables to create expressions. Kaya supports:

  • Arithmetic: +, -, *, /, %
  • Comparison: >, >=, <, <=, ==, !=
  • Logical: &&, ||, !
  • Unary: -, +, !
  • Member access: ., [], ?.
  • Null coalescing: ??
  • Ternary conditional: ? :
  • AI operators: is (semantic match), as (type cast)

There are no === / !== operators — writing them is a parse error. == and != use JavaScript-style loose coercion. See Differences from JavaScript.

All examples below are complete, valid statements. Bare expressions (5 + 3 on its own line) do not parse — bind results with let, or use an echo string or function call.

Precedence

The single authoritative precedence table lives in the Syntax Reference. Highlights:

  • as binds tighter than every unary and binary operator — it attaches to the immediately preceding operand (a + b as number casts only b).
  • is sits at the equality level (==/!=) but has composability restrictions (see is).
  • ?? binds looser than || and &&, and may be freely mixed with them (no parentheses required, unlike JavaScript).
let a = 2 + 3 * 4          // 14 — multiplication first
let b = (2 + 3) * 4        // 20 — parentheses override
let c = x > 5 && y < 10    // comparisons bind tighter than &&

Arithmetic Operators

Addition (+)

Numbers add; if either operand is a string, both are coerced to strings and concatenated.

let sum = 5 + 3                  // 8
let text = "hello" + " world"    // "hello world"
let label = "Count: " + 42       // "Count: 42"

Subtraction (-), Multiplication (*), Modulo (%)

Operands are coerced to numbers.

let diff = 10 - 4       // 6
let product = 6 * 7     // 42
let remainder = 10 % 3  // 1
let isEven = n % 2 == 0

Division (/)

let quotient = 15 / 2   // 7.5

Division by zero throws a runtime error (Division by zero). It does not produce Infinity or NaN.

Comparison Operators

All comparison operators return booleans.

Relational (>, >=, <, <=)

let high = score > 90
let passing = score >= 60
let cold = temp < 0
let capped = count <= max

Equality (==) and Inequality (!=)

Scalar comparisons use loose, type-coercing equality (similar to JavaScript == semantics): numbers and strings are compared after numeric coercion, booleans coerce to numbers, and null equals undefined.

let same = 5 == "5"        // true (string coerced)
let active = status == "active"
let nonzero = count != 0

Unlike JavaScript (where objects and arrays compare by reference identity), Kaya treats containers as pure values with deep structural equality:

  • Arrays compare element-by-element ([1, 2] == [1, 2] is true).
  • Objects compare by structural equivalence across matching keys, key-order insensitive ({a: 1, b: 2} == {b: 2, a: 1} is true).
  • Leaves inside containers use strict equality without coercion ([1] == ["1"] is false, and [{a: null}] == [{a: undefined}] is false).
  • Heterogeneous comparisons across different container types or between containers and scalars evaluate directly to false ([1] == 1 is false, {} == "" is false).

There is no strict variant: 5 === 5 is a parse error. When scalar coercion matters, normalize first (e.g. value as number).

Logical Operators

&& and || are value-returning with short-circuit evaluation, exactly like JavaScript — they return one of their operands, not a boolean.

Logical AND (&&)

Returns the first falsy operand, or the last operand if all are truthy. The right side is not evaluated when the left is falsy.

let r1 = 5 && 10               // 10
let r2 = 0 && 10               // 0 (first falsy)
let ok = isLoggedIn && hasPermission

Logical OR (||)

Returns the first truthy operand, or the last operand if all are falsy. The right side is not evaluated when the left is truthy.

let r1 = 5 || 10               // 5 (first truthy)
let name = userName || "Guest" // falsy fallback (also catches "" and 0)

Use ?? instead when 0, "", or false are valid values.

Logical NOT (!)

Coerces to boolean and negates. Falsy values: false, 0, "", null, undefined, NaN; everything else is truthy.

let disabled = !isActive
let asBool = !!value     // coerce to boolean

Unary Operators

let neg = -5
let flipped = -(x + y)
let num = +"42"          // 42 — unary plus coerces to number
let one = +true          // 1

Member Access Operators

Dot Notation (.)

let userName = user.name
let city = user.address.city

Accessing a missing property returns undefined (no error). Accessing any property on null/undefined throws — use ?..

Bracket Notation ([])

Computed access with any expression as the key/index.

let first = items[0]
let nth = items[i]
let value = data["key"]
let name = users[0].name

Out-of-bounds and negative array indices THROW a runtime error (Array index out of bounds) — unlike missing object properties, which return undefined. There is no Python-style items[-1]; use items.slice(-1) or items[n] with a computed index in range.

Optional Chaining (?.)

Returns undefined (not null) when the object is null/undefined.

let name = user?.name                  // undefined if user is null
let city = user?.address?.city         // chain ?. at every step
let display = user?.name ?? "Guest"

?. protects only the access it is attached to — later non-optional links in the chain can still throw, so chain ?. at each potentially-missing step. Computed optional access (items?.[0]) is supported and yields undefined when items is null/undefined.

Ternary Operator

let status = temp >= 30 ? "hot" : "cold"
let discount = isPremium ? 0.2 : 0.1

// Right-associative: a ? b : c ? d : e  ==  a ? b : (c ? d : e)
let grade = score >= 90 ? "A" : score >= 80 ? "B" : "C"

Only the selected branch is evaluated.

Null Coalescing Operator

left ?? right returns left unless it is null or undefined. Unlike ||, it does not treat 0, "", or false as missing.

let displayName = userName ?? "Guest"
let count = savedCount ?? 0            // keeps a real 0
let pick = a ?? b ?? c ?? "default"    // first non-null/undefined

// Mixing with && / || is allowed (?? binds loosest)
let v = isReady && cached ?? fallback  // (isReady && cached) ?? fallback

Note: there is no undefined literal in Kaya — writing undefined parses as an ordinary identifier and fails as a missing variable. undefined values arise from missing properties, ?., and optional parameters.

Semantic Match (is)

<value> is <description-or-Type> asks an LLM whether the value semantically matches a description (or a type carrying an is: constraint) and yields a boolean. It is an async, LLM-backed operator.

// Direct condition (the most common form)
if userMessage is "an intent to leave the conversation" {
  "Goodbye!"
}

// Against a semantic type
type PositiveMessage = string + { is: "positive sentiment" }
if message is PositiveMessage {
  "Matched"
}

// Standalone let-binding is legal
let leaving = msg is "an intent to leave the conversation"

Composability:

  • ✅ Direct if / else if / while condition, or a standalone let binding.
  • ❌ Combining with && or || is a parse error.
  • ⚠️ Combining with the ternary (? :) or ?? parses but fails at runtime (the async LLM call cannot complete mid-expression). Bind to a variable first, then combine.
// ❌ parse error:
// if x == 3 && foo is "positive" { }

// ✅ bind first, then combine
let positive = foo is "positive"
if x == 3 && positive {
  "both"
}

For OR-style logic, use else if chains; for AND-style logic, nest if blocks or pre-bind each match as above.

See also: Semantic Constraints

AI Type Casting (as)

<value> as <Type> casts a value to a type, choosing one of three execution tiers by target-type complexity:

  1. Deterministic (no LLM): primitives — "123.45" as number, 42 as string, "true" as boolean, "123.9" as int.
  2. LLM classification: unions of string literals with is: constraints — the LLM picks the matching member.
  3. LLM transformation: object/array types — the LLM maps unstructured input into a validated, conforming instance.
let n = "123.45" as number      // 123.45 — deterministic

type Sentiment = "positive" + { is: "expressing happiness or approval" }
               | "negative" + { is: "expressing frustration or criticism" }
               | "neutral"  + { is: "objective, factual, or balanced" }
let mood = feedback as Sentiment            // LLM classification

type Contact = { firstName: string, lastName: string }
let contact = rawBio as Contact             // LLM transformation

Precedence: as binds tighter than every unary/binary operator — it attaches to the immediately preceding operand. a + b as number casts only b; -y as number negates the cast result.

Gotcha: x as string + "suffix" is a parse error — after a type name, + starts a constraint block (string + { ... }), not concatenation. Parenthesize: (x as string) + "suffix", or bind the cast to a variable first. Since tiers 2–3 run async LLM calls, standalone assignments (let x = val as Type) are the recommended form anyway.

In conditions: as boolean works directly as an if / else if condition — this is the explicit form for LLM-judged branching (symmetric with is):

if generate(message: "Is it hot in {{city}}?") as boolean {
  "Stay hydrated"
} else if fallbackAnswer as boolean {
  "Maybe"
}

Like all calls, generate(...) is only allowed inline in the first condition; for else if, bind the result to a variable first.

See also: AI Type Casting guide

See Also