CodeBlanks Logo Icon CodeBlanks

Summary - Tuple

Write labeled coordinate data using tuples.

Tuple summary

A tuple is the type-safe way to group a few related values in a fixed length and order. You make it immutable with readonly, and reach elements by index or destructuring. It fits small but structured data such as labeled coordinate values.

let nokta: readonly [string, number, number] = ["A", 5, 10];
let [etiket, x, y] = nokta;
console.log(etiket);  // "A"

Tuples are most useful for data that needs a few elements, a clear type order and fixed length.

Practice Labeled coordinate tuple

Define a readonly tuple named nokta with type readonly [string, number, number] and value ["A", 5, 10]. Destructure it into etiket, x and y. Print the value of etiket with console.log.

Starter code

index.ts
// nokta adında readonly bir tuple tanımla
// üç öğeli: string, number, number
// değer olarak bir etiket ve iki koordinat gir
// nokta'yı etiket, x, y değişkenlerine ayır
// etiket değişkenini yazdır

Sample solution

index.ts
let nokta: readonly [string, number, number] = ["A", 5, 10];
let [etiket, x, y] = nokta;
console.log(etiket);

Expected output

A

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In <code>let p: readonly [string, number] = ["x", 5]; let [s, n] = p;</code>, what is <code>n</code>?

  • 5 Correct answer
  • "x"
  • [string, number]
  • undefined

Explanation: Destructuring assigns the second position to <code>n</code>; the tuple's second element is of type <code>number</code> with value <code>5</code>. Being readonly does not block destructuring.

2 Print the y coordinate

Question
let nokta: readonly [string, number, number] = ["A", 5, 10];
let [etiket, x, y] = nokta;
console.log(____);
Answer
let nokta: readonly [string, number, number] = ["A", 5, 10];
let [etiket, x, y] = nokta;
console.log(y);

Explanation: The variable <code>y</code> holds the third position's number (10); <code>etiket</code> and <code>x</code> print other values, while <code>nokta</code> prints the whole tuple.

3 Tuple concepts

Term Meaning
readonly [string, number, number] Three-element immutable tuple
let [a, b, c] = t Destructure into three variables
t[2] Access the third element
Tuple Fixed-length ordered array

All lessons in Beginner