CodeBlanks Logo Icon CodeBlanks

Namespace vs module

Learn the difference between namespace and module.

Namespace vs module

A namespace groups related code under a name in the global scope. A module is file-based; each file has its own scope and connects via import/export. Modules are recommended for new projects; namespaces are an older pattern.

// namespace pattern (legacy)
namespace Hesap {
  export function topla(a, b) { return a + b; }
}

// module pattern (modern)
// file: hesap.ts
export function topla(a, b) { return a + b; }

When to use a namespace?

Namespaces are still useful when porting legacy JavaScript libraries to TypeScript or for single-file utilities. But for a modern project spanning multiple files, modules are more appropriate; they provide per-file independent scope and explicit dependency declarations.

Practice Legacy-pattern library header

Using the object pattern that is the compiled equivalent of a namespace structure, define an object named Kutuphane. It should have methods ekle(): string and sil(): string; ekle returns "eklendi", sil returns "silindi". Call them from outside as Kutuphane.ekle and Kutuphane.sil, printing the results on separate lines.

Starter code

index.ts
// Kutuphane adında bir nesne tanımla
// ekle metodunu ekle, "eklendi" döndürsün
// sil metodunu ekle, "silindi" döndürsün
// her ikisini de çağır, sonuçları ayrı satırda yazdır

Sample solution

index.ts
const Kutuphane = {
  ekle(): string {
    return "eklendi";
  },
  sil(): string {
    return "silindi";
  }
};
console.log(Kutuphane.ekle());
console.log(Kutuphane.sil());

Expected output

eklendi
silindi

Questions and answers

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

1 What is the recommended code organization for a new TypeScript project?

  • A single large namespace in one file
  • File-based module usage Correct answer
  • Only global variables
  • No organization at all

Explanation: For new projects, file-based module usage is recommended. Namespaces are a legacy pattern; global variables and no organization are bad practice.

2 Declare a namespace

Question
____ Hesap {
  export 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 group in the global scope you use the namespace keyword. module is file-based; package and scope are not keywords for declaring a namespace in TypeScript.

3 Namespace and module comparison

Term Meaning
namespace Ad { } Global scope grouping
import { } from "./mod" File-based import
Ad.üye Namespace member access
her dosya kendi kapsamında Module encapsulation rule

All lessons in Intermediate