CodeBlanks Logo Icon CodeBlanks

Readonly vs const

Learn the difference between readonly and const.

readonly vs const

const is for standalone variables, readonly is for class fields. const prevents reassigning the variable; readonly makes the field immutable after construction.

const MAX = 100;
class Config {
  readonly limit: number = MAX;
}

Which one in which case?

Use const for a standalone constant and readonly for a class field. const is not valid in a class body; readonly only works on class members.

// Standalone constant:
const VERSION = "1.0";
// Class field:
class App {
  readonly version: string = VERSION;
}

Practice App class with a readonly field

Define an App class with a readonly version: string = "1.0" field (with an initial value). Create a new App and print the version field.

Starter code

index.ts
// App sınıfı tanımla (değiştirilemez sürüm alanı, başlangıç değeri 1.0)
// yeni App oluştur, version'ı yazdır

Sample solution

index.ts
class App {
  readonly version: string = "1.0";
}

const a = new App();
console.log(a.version);

Expected output

1.0

Questions and answers

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

1 Which is used to make a class field immutable?

  • readonly Correct answer
  • static
  • const
  • let

Explanation: readonly is used for class fields. const is not valid in a class body; it is only for standalone variables. let is mutable, and static is a class-level modifier.

2 Complete the right modifier for a class field

Question
class App {
  ____ version: string = "1.0";
}
Answer
class App {
  readonly version: string = "1.0";
}

Explanation: To make a class field immutable you use readonly. const is invalid in a class body, static moves to the class level (mutable), and public opens access (mutable).

3 readonly vs const parts

Term Meaning
const Constant for a variable
readonly Constant for a class field
const MAX = 100 Standalone constant
readonly limit: number Class constant field

All lessons in Intermediate