Syntax Basics

Variables, types, expressions, and data structures

Variables

Variable Declaration (let)

Use let to declare new variables. Variables declared with let are lexically block-scoped (meaning they are isolated to the block, function, or loop body in which they are defined):

// Declare variables
let name = "Alice"
let age = 30
let isActive = true

// With interpolation
let greeting = "Hello, {{name}}!"

// With expressions
let nextAge = age + 1

Variable Reassignment and Scoping

To update or reassign an existing variable, use a bare assignment (without the let keyword).

Kaya supports precise lexical block-scoping. Declaring a variable with let inside a nested scope (like an if block or a loop body) that shares a name with an outer variable will shadow that variable. This creates an isolated local variable on the execution stack. To modify the outer scope variable instead of shadowing it, use bare assignment:

let content = "original"

for filename in ["a.html", "b.html"] {
  // Shadowing: Declares a local variable in the loop's local scope.
  // This does NOT affect the outer 'content' variable.
  let content = "loop-local"
}
// content is still "original"

for filename in ["a.html", "b.html"] {
  // Mutation: Modifies the existing 'content' variable in the outer scope.
  content = "updated"
}
// content is now "updated"

Constant Declaration (const)

Use const to declare immutable values that cannot be reassigned:

const PI = 3.14159
const MAX_RETRIES = 5

// ❌ This would error:
// const name = "Alice"
// name = "Bob"  // Error: Cannot reassign const variable

Type Annotations

Explicitly declare variable types for runtime validation:

// Built-in types
let name: string = "Alice"
let age: number = 30
let active: boolean = true
let data: json = {"key": "value"}

// Array types
let names: string[] = ["Alice", "Bob"]
let scores: number[] = [95, 87, 92]

// Custom types
type User = {
  name: string,
  age: number
}

let user: User = {
  name: "Alice",
  age: 30
}

Type Subtypes

Add semantic meaning to types with subtypes:

// String subtypes
let markdown: string/markdown = "# Hello"
let html: string/html = "<h1>Hello</h1>"

// Number subtypes
let percentage: number/percentage = 75

// File subtypes annotate file OBJECTS returned by stdlib calls —
// a path string like `let photo: file/png = "photo.png"` fails validation
let photo: file/png = generateImage(prompt: "A sunset")

// In function parameters
function renderDoc(content: string/markdown) {
  "Rendering markdown: {{content}}"
}

Common subtypes:

  • Strings: markdown, json, xml, yaml, csv, html
  • Files: png, jpg, pdf, svg
  • Numbers: percentage

Expressions

Kaya supports JavaScript-like expressions for computations.

Literals

// Numbers
let count = 42
let price = 19.99
let negative = -10

// Strings
let name = "Alice"
let quote = 'Hello'
let template = `Template string`

// Booleans
let isTrue = true
let isFalse = false

// Null
let empty = null

Operators

Kaya supports JavaScript-style operators. The Operators Reference covers each in detail and the precedence table is the single source of truth for evaluation order. A quick tour:

// Arithmetic (division by zero throws)
let sum = 5 + 3           // 8
let result = 2 + 3 * 4    // 14 — standard precedence
let grouped = (2 + 3) * 4 // 20 — parentheses override

// Comparison — only loose == and != exist (no === / !==)
let active = status == "active"
let nonzero = count != 0

// Logical — value-returning, short-circuiting
let canGo = temp >= 30 && isSunny
let hasAccess = isAdmin || isOwner
let enabled = !isDisabled

// Ternary (right-associative; no parentheses needed when nesting)
let category = temp >= 30 ? "hot" : temp >= 15 ? "warm" : "cold"

// Null coalescing — only null/undefined trigger the fallback
let displayName = userName ?? "Guest"
let count2 = savedCount ?? 0          // keeps a real 0

// Member access
let city = user.address.city          // missing property → undefined
let first = items[0]                  // out-of-bounds/negative index THROWS
let value = data.users[0].name

// Optional chaining — yields undefined (not null) when the object is missing
let name = user?.name
let town = user?.address?.city ?? "Unknown"

// Unary
let opposite = -value
let num = +stringValue                // coerce to number
let hasNoItems = !items.length

Things that differ from JavaScript (full list in the syntax reference): ===/!== are parse errors; ?? mixes freely with &&/||; out-of-bounds array indexing throws instead of returning undefined; and bare expression statements (5 + 3 on a line by itself) don't parse — bind results with let.

Data Structures

Arrays

// Array literals
let numbers = [1, 2, 3, 4, 5]
let names = ["Alice", "Bob", "Charlie"]
let mixed = [1, "two", true, null]

// Empty arrays
let empty = []

// Nested arrays
let matrix = [[1, 2], [3, 4]]

// With expressions
let calculated = [x, y, x + y, x * y]

// Arrays of objects
let users = [
  {name: "Alice", age: 30},
  {name: "Bob", age: 25}
]

// Accessing elements
let first = numbers[0]
let last = numbers[4]
let nested = matrix[0][1]

Objects

// Object literals
let person = {name: "Alice", age: 30}
let config = {width: 800, height: 600}

// Empty objects
let empty = {}

// With expressions
let dimensions = {
  w: 100,
  h: 200,
  area: 100 * 200
}

// Nested objects
let data = {
  user: {name: "Bob", active: true},
  scores: [95, 87, 92]
}

// Multiple quote styles (all equivalent)
let obj1 = {name: "Ted"}
let obj2 = {"name": "Ted"}
let obj3 = {'name': 'Ted'}
let obj4 = {name: `Ted`}

// Accessing properties
let userName = person.name
let width = config.width
let firstScore = data.scores[0]

Shorthand properties

When a property value is a variable with the same name as the key, you can drop the key: and write just the variable. { name } is shorthand for { name: name }:

let name = "Alice"
let age = 30

// Shorthand — these two are identical
let person = { name, age }
let personLong = { name: name, age: age }

// Mix shorthand with explicit properties, in any order
let user = { name, role: "admin", age }

Shorthand only applies to identifier keys — a quoted key like { "name" } has no variable to reference, so it stays an error. See Fully Specified Argument Calling for why Kaya keeps keys explicit everywhere else.

Template Interpolation

See Templating for variables, expressions, and Liquid filters inside strings.

Type System

See Type System for built-in types, custom definitions, array types, and structural and semantic constraints.

Comments

// Single-line comment
let x = 10  // Comment after code

/* Block comment */
let y = 20

/*
  Multi-line
  block comment
*/

/* Inline block */ let z = 30

Block comments don't nest. The first */ always closes the comment, and whatever follows is parsed as code:

/* outer /* inner */ let a = 1
// The comment above ended at the FIRST */ — `let a = 1` is real code.
// A trailing "still inside outer */" would be a parse error.

Truthy and Falsy Values

In conditions, values are evaluated as truthy or falsy:

Falsy values:

  • false
  • 0
  • null
  • undefined (not a literal you can write — it arises from missing properties, ?., and unset optional parameters)
  • "" (empty string)

Truthy values:

  • Everything else!
let count = 5
if count {
  "Count is truthy"  // ✓ Executes
}

let zero = 0
if zero {
  "Won't print"      // ✗ Skipped (0 is falsy)
}

// Common pattern: default values
let value = input ?? "default"

Type Coercion

Kaya uses JavaScript-like type coercion:

// String + number = string
let result = "Score: " + 42  // "Score: 42"

// String * number = number
let product = "10" * 2  // 20

// Boolean in arithmetic
let sum = true + 1  // 2
let diff = false + 1  // 1

// Boolean in logical operations (value-returning)
let yes = true && "yes"   // "yes"
let no = false || "no"    // "no"

Best Practices

  1. Use const for constants: Values that never change
  2. Type annotate function parameters: Catch errors early
  3. Use optional chaining: Prevent null reference errors
  4. Prefer expressions over templates: age + 1 vs "{{age}} + 1"
  5. Use semantic types: Make intent clear with .is()

Next Steps