Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

In JavaScript, a Factory controls how an object is created, while a Singleton makes one instance or state holder intentionally shared within a defined scope. Choose a Factory when the implementation may vary or callers should not need to know construction details; choose a Singleton only when shared identity or coordination is genuinely required. Neither pattern is a universal default: ordinary object creation and explicit dependency injection are often clearer.

At a glance

Name Best for Key distinction Typical scope Checked
Factory Choosing or hiding how an object is constructed Can create many objects, including different implementations Each call or caller-managed lifetime Nov 2026
Singleton Sharing one coordinator, identity, or state holder Reuses one instance within a named boundary Module, window, application, or another explicit scope Nov 2026

What is the difference between Singleton and Factory in JavaScript?

A Factory is a creation boundary; a Singleton is a reuse and sharing rule. They answer different questions: “How should this object be made?” versus “Should callers share the same object or state?”

A factory function can return a fresh object on every call, select one of several concrete implementations, or configure an object before returning it. A Singleton intentionally exposes one shared instance or state holder within a scope. A Factory can even create a Singleton, but the patterns are not interchangeable: one concerns construction, the other concerns identity and lifetime.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Question Factory Singleton
Primary purpose Hide or centralize construction choices Coordinate intentionally shared state or identity
How many objects? Often many; each call may create a new object One reused object within the stated scope
How does the caller get it? Calls a function or creation method, or receives one by injection Uses an accessor or imports a module-owned object
What should be explicit? The implementation choice or creation boundary The boundary in which the instance is shared
Common trade-off Another layer to maintain if construction is already simple Implicit access and state that can complicate isolation

MDN’s explanation of the new operator makes the ordinary baseline clear: “Each time you call new, a different instance is created.” A Factory may use new internally, but the caller does not have to select the concrete constructor. The W3C Design Principles likewise caution that “Factory methods can complement constructors, but generally should not be used instead of them.” A factory is useful when it hides a meaningful decision, not as ceremony around every new.

Popular on Amazon
Silkland 40Gbps USB C 90 Degree Right Angle Adapter 2 Pack, 240W USB4 | Male to Female Extender, 8K@60Hz, Thunderbolt 4/3, Steam Deck, ROG Ally, MacBook, Switch 2, iPhone 18/17/16/15, Quest 3 VR
  • 【90 Degree Full Function USB C Adapter】Supports the latest USB4 standard for up to 40Gbps of bandwidth, 8K video support, and up to 240W Fast charging; Support USB PD 3.1 Extended Power Range (EPR) including 140W, 180W and 240W. Your productivity is easily doubled. *Warm Tip: For the best fit, please make sure the USB-C port is fully exposed; thick or bulky cases may affect compatibility.
  • 【Reliable Quality】Made from high-quality, scratch-resistant aluminum alloy, delicate metal frame. get excellent wear resistance and heat dissipation. Non-Slip Design for easier insertion and removal.
  • 【Small and portable】Ultra thin size, ultra compact design, a petite physique that matches the minimalist design of your modern laptops. Coming with a slim figure that won't block the port next to the one it's plugged into.
  • 【Compatibility】Widely work with most usb c, thunderbolt 4/3 devices. Compatibilit for ROG Ally, Steam Deck, Switch, MacBook Pro, Quest 3 VR headset, Surface Book 2, iPhone 18/17/16/15, Samsung Galaxy S23/S22/S21, Note 20/10, Google Pixel, ChromeBook, etc.
  • 【Excellence Customer Support】If you experience any issues or cable failure, simply reach out to our dedicated customer service team. We provide a prompt response within 18 hours, providing you with the necessary technical support to resolve any concerns.

What is a Factory pattern in JavaScript?

A Factory is a function or method that creates an object while keeping concrete construction details behind a named boundary. Callers request the capability or kind of object they need instead of assembling or selecting every implementation themselves.

For example, a notification feature could support email and SMS. The rest of the application can rely on both objects having a send method:

class EmailNotifier {
  send(message) {
    return `Email: ${message}`;
  }
}

class SmsNotifier {
  send(message) {
    return `SMS: ${message}`;
  }
}

function createNotifier(channel) {
  switch (channel) {
    case "email":
      return new EmailNotifier();
    case "sms":
      return new SmsNotifier();
    default:
      throw new Error(`Unsupported channel: ${channel}`);
  }
}

const notifier = createNotifier("email");
console.log(notifier.send("Your receipt is ready"));

The useful boundary is createNotifier. A caller does not need to know which class to instantiate, and the supported choices and failure for an unsupported channel are visible in one place. If a new implementation is added, the creation decision can be updated there rather than scattered across call sites. The example still creates a new notifier whenever the factory is called; it does not imply that the returned object is shared.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In a larger application, the factory might also accept configuration, choose an adapter based on runtime settings, or look up a registered implementation. Keep the choice proportionate: for a fixed, trivial object, a direct constructor or object literal is simpler. If the factory’s switch keeps growing, a registry can centralize mappings, but that registry is still a creation mechanism—not automatically a Singleton requirement.

A browser factory example

Factories need not be custom classes or elaborate frameworks. The browser’s document.createElement() API is a familiar factory-style interface: request an element by name and the browser returns the corresponding element object, handling its concrete construction details.

const button = document.createElement("button");
button.textContent = "Save";

const label = document.createElement("label");
label.textContent = "Email address";

This demonstrates the pattern’s central idea, not a claim that every factory must follow a formal class hierarchy. In JavaScript, factories commonly appear as plain functions, static methods, registry lookups, or platform APIs.

Also popular on Amazon
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

What is a Singleton pattern in JavaScript?

A Singleton provides one intentionally shared instance or state holder inside a defined scope. The phrase “one instance” is incomplete unless you say one per what: module instance, browser window, application, bundle, worker, or process.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For example, navigator, history, and crypto are browser-provided services available through a window or global environment. The W3C Design Principles discusses such objects as singleton-like platform objects. They illustrate scoped shared services; they do not mean every application service should become a global Singleton.

Likewise, a module can own shared state without exporting a class whose constructor tries to prevent all other instances:

// settings.js
const settings = new Map();

export function getSettings() {
  return settings;
}
// feature.js
import { getSettings } from "./settings.js";

const settings = getSettings();
settings.set("theme", "dark");

Within a given loaded module instance, imports provide access to the module-owned map. MDN’s JavaScript modules documentation describes the import/export model that makes this approach possible. The scope qualification matters: duplicated bundles, separate realms, workers, or separate application processes may have separate module instances and therefore separate maps. This is not a cross-tab or process-wide storage guarantee.

For state that is only needed by one part of a feature, keeping it local or passing it to the components that need it is often easier to reason about than exporting a shared module object. Shared access is justified when multiple parts of the application must coordinate through the same identity or state, not merely because a convenient import is available.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do I create a Singleton with a JavaScript class?

JavaScript has private class fields but no native private constructor. A class can guard construction and expose an accessor, but the guard is an implementation convention rather than a language feature that makes every alternate construction path impossible.

Also popular on Amazon
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
class AppConfig {
  static #instance;

  static getInstance() {
    return (AppConfig.#instance ??= new AppConfig());
  }

  constructor() {
    if (AppConfig.#instance) {
      return AppConfig.#instance;
    }

    this.environment = "production";
  }
}

const first = AppConfig.getInstance();
const second = AppConfig.getInstance();

console.log(first === second); // true

The private static field #instance keeps the reference inside the class. The first call to getInstance() constructs an object and stores it; later calls return the stored reference. The constructor guard also makes direct calls to new AppConfig() return the existing object after initialization. MDN documents private class elements and private static elements; they help encapsulate this state, but JavaScript does not supply a dedicated private-constructor keyword.

That distinction affects how strongly the pattern is enforced. The class is intentionally designed to reuse its object, but it is not the same as a language-enforced prohibition on all construction. For many applications, a module-owned service or an object created once by an application container is more straightforward than adding a Singleton class solely to hide its constructor.

Do not use a Singleton as a shortcut for dependency injection. If a component reaches into a global accessor whenever it needs a service, its dependency is less visible and harder to replace. Passing the service in a constructor or function parameter makes that relationship explicit and allows the caller to control lifetime.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When should I use a Factory, and when should I use a Singleton?

Use a Factory when construction choices need a stable boundary. Use a Singleton only when one shared identity within a clearly named scope is part of the requirement.

  • Choose a Factory when input or configuration determines the concrete type; you expect implementations such as transports, adapters, or plugins to vary; setup should be centralized; or tests need to supply a substitute through a visible creation boundary.
  • Choose a Singleton when multiple parts of one defined scope must coordinate through the same object, such as a shared registry or cache, and the team accepts its lifetime and state-reset implications.
  • Choose ordinary construction when the object is simple and the caller should own its lifetime. A direct new SomeService(options) is often clearer than a factory or Singleton wrapper.
  • Choose dependency injection when a container or application composition root should create a service once and pass it to consumers. This can provide shared lifetime without making a hidden global accessor the only way to obtain it.

The key distinction is that a Factory does not have to return the same object twice, and a Singleton does not have to offer multiple implementation choices. If a requirement says “the right implementation depends on the environment,” start with a factory. If it says “these consumers must coordinate through this same state,” define the scope and then decide how to provide that shared state.

How do Factories and Singletons affect testing?

Factories usually make substitutions easier because the creation boundary is explicit: a caller can receive a fake factory or a test implementation. A Singleton can also be tested, but persistent shared state needs deliberate isolation so one test’s changes do not affect another.

Also popular on Amazon
BENFEI USB C Hub 5-in-1 with 4K HDMI(Certified), 100W Power Delivery, 3 USB-A, Silicone Cable, Aluminum Case Compatible with MacBook Pro/Air, iPad Pro, iMac, iPhone 15 Pro/Pro Max, XPS, Thinkpad
  • Portable and powerful USB-C HUB: BENFEI USB Type-C HUB, with super-soft and knot-free silicone woven design cable, meets most mobile office needs. Compact, lightweight, stylish, and powerful portable USB C Hub equipped with 1 x HDMI port, 1 x 100W charging, and 3 x USB ports. 18-month warranty, 24-hour response, to ensure you feel at ease when using our product.
  • Design centered on comfort and reliability: Thanks to BENFEI's end-to-end in-house cable production capability, in-house PCBA and assembly capability, using the industry's most advanced silicone woven design and process, 20cm cable in length, no knots, super-soft, the HUB is easy to use in all scenarios: laptop, tablet, stand etc. Super-soft, 25000+ life cycles, to meet your daily carrying and office needs.
  • 100W Charging: Support up to 90W USB C pass-through charging via Type-C port to keep your laptop powered. 10W is reserved for other interface operations. No data and video function on the Type-C port.
  • 4K HDMI Display: The HDMI port supports media display at resolutions up to 4K 30Hz, keeping every incredible moment detailed and ultra vivid. Please note that the C port of the Host device needs to support video output.
  • Transfer Files in Seconds: Transfer files and from your laptop at speeds up to 10 Gbps with USB A 3.2 port. Extra 2 USB A 2.0 ports are perfectly for your keyboards and mouse.

This is a practical design trade-off, not a claim that either pattern guarantees testability. For example, a factory can accept a dependency or be replaced at the composition boundary. A module-scoped Singleton may need a reset mechanism, a fresh module environment, or careful test setup when its state changes. Each reset mechanism adds lifecycle behavior that the application and tests must understand.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Prefer testing a consumer with a dependency passed in directly when possible. That makes its requirements visible and avoids coupling every test to a hidden global accessor. If a shared instance is necessary, keep its state small, document who owns it, and make any test isolation strategy explicit rather than relying on test order.

What mistakes should I avoid?

The most common mistake is treating either pattern as automatically beneficial. Add a creation boundary or shared instance only when it solves a concrete problem.

  • Calling every factory a Singleton: a factory may return a fresh object each time. State its reuse behavior separately.
  • Calling every module export globally unique: module sharing applies within a module instance, not automatically across duplicated bundles, realms, workers, windows, or processes.
  • Using a Singleton for convenience alone: global reach can hide dependencies and make state changes harder to trace. Pass dependencies explicitly when that improves clarity.
  • Replacing constructors everywhere with factories: W3C guidance says factories can complement constructors and generally should not replace them. Use a factory when the creation decision is useful to centralize.
  • Ignoring lifetime: a shared cache or registry can persist longer than a component expects. Decide who initializes it, who can mutate it, and when it is reset or discarded.
  • Assuming one instance means one per entire JavaScript ecosystem: browser windows, module instances, workers, and application processes have distinct boundaries. Name the intended boundary in design discussions and code documentation.

There is no performance figure that settles this choice. The relevant decision is architectural: whether construction needs abstraction, whether shared identity is required, and whether the resulting lifetime is understandable to callers and tests.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How should I decide for a real feature?

Write down the behavior before selecting a pattern. A short design check often prevents an unnecessary abstraction:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Identify the changing decision. Does configuration select an implementation, or is the object itself straightforward to construct?
  2. Identify the required identity. Do consumers need one shared object, or would separate instances work just as well?
  3. Name the scope. If one shared object is needed, specify module, window, application, or another exact boundary.
  4. Choose who owns creation and lifetime. It may be a factory, the caller, or an application container. Avoid letting a global accessor silently decide both.
  5. Check the test seam. Can a consumer receive a substitute? If shared state persists, how will tests isolate or reset it?
  6. Keep the smallest solution. Start with direct construction if no meaningful variation or sharing requirement exists, then introduce a pattern when the requirement appears.

For a configurable notifier, the type-selection requirement points toward a Factory. For a registry that truly must be shared by features within one application module, module-owned state may be enough. For a stateless service used in one place, neither pattern may add value. The pattern follows the requirement, not the other way around.

Also popular on Amazon
𝟒𝐏𝐚𝐜𝐤 𝐔𝐩𝐠𝐫𝐚𝐝𝐞𝐝 USB to USB C Adapter,Type-C Female to A Male Charger Converter for iPhone 18 Charger,iWatch Ultra SE 9 10,iPhone 17 Pro Max 16 15 14,Samsung S25,AirPods,iPad,Car,Xbox
  • 【Read before You Buy】 Note: This adapter is USB 2.0 version and cannot transmit HDM, VGA, or other video signals. Nevertheless, they are fully capable of charging devices,duplicating files, and can be seamlessly integrated with USB-C earphones, wireless network adapters, and SD card adapters.
  • 【Easy to Use and Safe】Thanks to modern manufacturing techniques, we've made these adapters sufficiently compact so that they can remain inserted in your device without noticeable protrusion or inconvenience. This means you don't have to constantly plug and unplug them, reducing the likelihood of wear and misalignment, and making them more convenient to carry around.
  • 【Reliable Quality】Engineered for enhanced durability, durable aluminum alloy shell material,get excellent wear resistance and heat dissipation,the male USB C and female USB connectors & the male USB and female USB C connectors are designed to be plugged and unplugged up to 20000 times. Provides data transfer, device charging, memory space expansion, and additional computer peripherals.
  • 【Think more for you】Do you need to connect a USB-C-enabled device to an odd device that only has USB-A ports? Then these USB-A male to USB-C female adapters are made for you.Simply insert the adapter into the USB-A port on the device, and you can instantly connect your USB-C device to the device that originally didn't have the correct connection port.
  • 【Trusted xiwxi Quality and Service】As a responsible brand seller, you will receive xiwxi's 12-month Quality assurance and lifetime friendly customer service, you're not just buying a product,you're investing in peace of mind with all-round quality and exceptional customer service.

What is the practical rule to remember?

Factory controls how objects are created; Singleton controls whether a shared object is reused. Factories can make implementation choices explicit and substitutable. Singletons can coordinate shared state, but only within a clearly defined boundary and with lifecycle consequences that the design accepts. For many JavaScript applications, module-scoped services or explicit dependency injection are clearer than a globally reachable Singleton.

Frequently Asked Questions

Is a JavaScript factory function the same as a constructor?

No. A constructor is commonly called with new to initialize an instance, while a factory function can return an object without requiring new and can choose among different implementations. A factory may call constructors internally, so they can work together.

Does a Singleton in one browser tab also exist in another tab?

Not by default. A module or window-scoped object belongs to that loaded environment; separate tabs have separate JavaScript environments, so sharing across tabs requires a separate communication or storage mechanism.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can a Factory return the same object every time?

Yes, a factory can return a cached or shared object, but doing so adds a reuse policy beyond the basic creation role. Document that behavior clearly so callers do not assume each factory call returns a fresh instance.

Does a Singleton make a JavaScript service faster?

There is no general performance guarantee from choosing the pattern. Choose it for required shared identity or coordination, and evaluate performance claims against a specific workload and credible measurements rather than assuming one instance is inherently faster.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply. Prices as of November 8, 2026 12:27 am GMT.