CodeBlanks Logo Icon CodeBlanks

What is a namespace?

Learn global scope grouping with namespace.

What is a namespace?

A namespace groups related code under a single name. It is declared with namespace Name { ... } syntax and members inside are exported with the export keyword. They are accessed from outside as Name.member.

namespace Hesap {
  export function topla(a: number, b: number) {
    return a + b;
  }
}
console.log(Hesap.topla(2, 3));  // 5

Without export it stays private

Members not marked with export inside a namespace are inaccessible from outside; they can only be used within the same namespace. This means a namespace provides encapsulation; you can hide internal logic from the outside world.

Practice Apply the namespace pattern

The compiled equivalent of a namespace structure can be expressed as a named object pattern. Define an object named Hesap with method topla(a: number, b: number): number returning a + b. Call it from outside as Hesap.topla with 2 and 3, and print the result with console.log.

Starter code

index.ts
// Hesap adında bir nesne tanımla
// topla metodunu ekle, a ve b parametreli
// a + b döndürsün
// topla'yı 2 ve 3 ile çağır, sonucu yazdır

Sample solution

index.ts
const Hesap = {
  topla(a: number, b: number): number {
    return a + b;
  }
};
console.log(Hesap.topla(2, 3));

Expected output

5

Questions and answers

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

1 How is a member inside a namespace accessed from outside?

  • Via super.member
  • Only by the member name directly
  • Via dot notation as Ad.member Correct answer
  • Via import { member } from "Ad"

Explanation: Namespace members are accessed via dot notation as Ad.member. import is for module imports; super is used in class inheritance; direct member access works only from inside the namespace.

2 Add export

Question
namespace Hesap {
  ____ function topla(a: number, b: number): number {
    return a + b;
  }
}
Answer
namespace Hesap {
  export function topla(a: number, b: number): number {
    return a + b;
  }
}

Explanation: To make a member inside a namespace accessible from outside you use export. public and static are for class members; default is for a module's default export.

3 Namespace parts

Term Meaning
namespace Ad Namespace declaration
export function Exported member
Ad.üye Dot access
export olmayan üye Only inside the namespace

All lessons in Intermediate