Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Knockout-js

Learn Knockout-js - 9 Code Examples & CST Typing Practice Test

Knockout.js is a lightweight JavaScript library that uses the MVVM (Model-View-ViewModel) pattern to create responsive, data-driven UIs with declarative bindings. It emphasizes simplicity, observables, and automatic UI updates.

View all 9 Knockout-js code examples →
Knockout.js Simple CounterKnockout.js Counter with StepKnockout.js Counter with Min/MaxKnockout.js Counter with HistoryKnockout.js Counter with Auto IncrementKnockout.js Counter with Double IncrementKnockout.js Counter with Even/Odd IndicatorKnockout.js Counter with LocalStorageKnockout.js Counter with Color Themes

Learn KNOCKOUT-JS with Real Code Examples

Updated Nov 23, 2025

Explain

Knockout enables dynamic UI updates using observable variables.

It provides a clean separation between data, logic, and UI using MVVM.

Knockout's declarative bindings allow HTML to stay simple and connected to data automatically.

Core Features

Observables for reactive data

Computed functions for derived state

Declarative HTML bindings

MVVM architecture

Extensible custom binding handlers

Basic Concepts Overview

Observables (`ko.observable()`)

Observable arrays

Computed observables

Declarative bindings (`data-bind`)

`applyBindings()` to activate Knockout

Project Structure

index.html - UI + bindings

viewmodels/ - JS logic layer

models/ - data structures

templates/ - reusable templates

lib/ - knockout + plugins

Building Workflow

Define viewmodel with observables

Bind HTML using `data-bind` syntax

Attach event bindings

Use computed values

Modularize viewmodels for larger apps

Difficulty Use Cases

Beginner: simple forms

Intermediate: dynamic templates

Advanced: large MVVM apps

Expert: custom binding handlers

Community: maintaining enterprise KO apps

Comparisons

Simpler than React - fully binding-based

Lighter than Angular - no heavy framework

No virtual DOM - relies on direct DOM bindings

Excellent for forms; not ideal for huge SPAs

Stable alternative for long-term enterprise apps

Versioning Timeline

2010 - KO 1.0 released by Steve Sanderson

2012 - KO 2.0 with improved bindings

2014 - KO 3.0 performance upgrades

2020-2025 - Maintenance mode; stable for enterprise apps

Glossary

Observable: reactive variable

ViewModel: logic layer controlling UI

Binding: declarative HTML connection to data

Computed: auto-updating derived value

Subscription: listener on observable changes

Installation Setup

Use CDN: `<script src='knockout.js'></script>`

Install via npm: `npm install knockout`

Load via Require.js or AMD

Add viewmodel JS files

Bind with `ko.applyBindings(viewModel)`

Environment Setup

Install KO via npm or CDN

Create viewmodel JS file

Add bindings to HTML

Load script with `<script>` tag

Activate MVVM using applyBindings

Config Files

package.json - KO installed

config.js - RequireJS config

webpack.config.js - bundling

index.html - binding root

viewmodel files - structure

Cli Commands

No official CLI

Use npm scripts for builds

Use Webpack/Vite commands

RequireJS for modular loading

Custom project scaffolding

Internationalization

Use separate i18n libraries

Bind translated strings

Observable locale changes

Localized templates

Integration with Globalize.js

Accessibility

ARIA roles bound with attributes

Keyboard event bindings

Semantic HTML support

Screen-reader friendly templates

Forms accessible via KO validation

Ui Styling

Pure CSS styling

Conditional bindings

Class/Style bindings

Works with Tailwind/Bootstrap

Custom animations with bindings

State Management

Local state via observables

Computed for derived state

Subscriptions for observers

External state stores optional

Custom plugins for global state

Data Management

Observable-based data handling

REST calls using fetch/axios

Mapping plugin for DTO conversion

Computed for cached values

Manual state flow control

Architecture

MVVM pattern (Model -> ViewModel -> View)

Observer-based reactivity

Declarative HTML bindings

Template-based UI reuse

Manually managed modules and viewmodels

Rendering Model

Direct DOM updates

Dependency tracking engine

Bindings evaluated during applyBindings

Computed observables trigger re-render

Template-based UI grouping

Architectural Patterns

MVVM architecture

Observable-driven reactivity

Event-driven interactions

Custom binding handlers

Modularized viewmodels

Real World Architectures

Enterprise dashboards

Internal corporate SPAs

Large form-based applications

Legacy .NET apps with KO frontends

Hybrid apps mixing KO + modern frameworks

Design Principles

MVVM separation

Declarative bindings

Automatic UI updates

Lightweight core

Extensible binding system

Scalability Guide

Use components for modularity

Break viewmodels per page/feature

Throttle frequent computed updates

Use observable arrays carefully

Lazy-load data where possible

Migration Guide

Modularize large viewmodels

Move to ES modules

Extract logic into services

Consider migration to React/Vue if needed

Use KO components to modernize

Performance Notes

Use computed observables efficiently

Avoid heavy DOM operations inside bindings

Minimize large observable arrays

Use throttling for frequent updates

Break large viewmodels into modules

Security Notes

Avoid injecting raw HTML via bindings

Use `text` binding instead of `html` for safety

Validate user-provided data

Use HTTPS for remote data

Avoid eval-based bindings

Monitoring Analytics

Use Sentry for errors

Track API failures

Monitor binding performance

Audit dependency cycles in computed

Debug bindings using KO context debugger

Code Quality

Use ESLint/Prettier

Prefer computed observables for derived logic

Avoid massive God-viewmodels

Document custom bindings

Write unit tests for logic

Practical Examples

Todo list with observables

Form with validation

Dashboard with live-updating values

Custom binding for DOM interactions

List rendering with templates

Troubleshooting

Check if `applyBindings()` was called

Validate computed dependencies

Ensure bindings match observable names

Debug circular computed dependencies

Check console for binding errors

Testing Guide

Test viewmodels using Jasmine/Mocha

Mock observables in tests

Test computed values

Test binding initialization

End-to-end UI tests using Cypress

Deployment Options

Deploy as static files

Bundle using Webpack/Rollup

Use inside legacy .NET frameworks

Integrate with server-side rendering

Host on any static site provider

Tools Ecosystem

Knockout Validation plugin

Knockout Mapping plugin

RequireJS for modular KO apps

Knockout Punches for enhanced bindings

Chrome Knockout context debugger

Integrations

Works with jQuery for AJAX

Integrates with REST APIs easily

Can be embedded within React/Vue as legacy layer

Works with Webpack, Parcel, Vite

Supports TypeScript definitions via DefinitelyTyped

Productivity Tips

Use mapping plugin for JSON

Keep bindings simple

Prefer computed for UI logic

Split huge viewmodels

Leverage Chrome KO debugging tools

Challenges

Build a two-way bound form

Create a computed value dashboard

Implement custom binding for animations

Create a templated list with sorting

Modularize a multi-view application

Learning Path

Learn observables

Understand computed and subscriptions

Master data-bind syntax

Build modular MVVM structures

Create custom bindings and templates

Skill Improvement Plan

Week 1: MVVM basics + observables

Week 2: Computed + event handling

Week 3: Templating + modularization

Week 4: Custom bindings

Week 5: Advanced architecture patterns

Interview Questions

What is MVVM in Knockout?

How do observables work?

What is a computed observable?

Differences between `text`, `html`, and `value` bindings?

How does dependency tracking work in Knockout?

Cheat Sheet

`ko.observable(val)` - create observable

`ko.observableArray([])` - array observable

`ko.computed(fn)` - computed state

`data-bind='text: name'` - bind values

`ko.applyBindings(vm)` - initialize bindings

Books

Knockout.js by Example

Knockout.js Essentials

Knockout.js Starter

Learning MVVM with Knockout

Professional Knockout.js

Tutorials

Knockout official tutorial

PluralSight KO MVVM courses

YouTube Knockout.js series

Egghead MVVM lessons

Legacy KO enterprise training series

Official Docs

https://knockoutjs.com/documentation/

https://github.com/knockout/knockout

https://learn.knockoutjs.com/

Community Links

Knockout GitHub

StackOverflow knockoutjs tag

Knockout Gitter community

Enterprise dev forums

Microsoft community archives

Community Support

Knockout GitHub repository

Stack Overflow knockoutjs tag

Gitter/Slack KO groups

MSDN legacy community

Enterprise internal communities

Monetization

Build enterprise dashboards

Maintain legacy KO systems

KO consulting/modernization

Migration services

Custom KO plugins and bindings

Future Roadmap

Continued long-term stability

Used mainly in maintenance mode

Improved TypeScript integration

Better tooling from community

Still valuable for legacy support

When Not To Use

When building massive SPAs

When needing modern UI patterns

When requiring large ecosystems and plugins

When needing SSR-first architecture

When team prefers component-based frameworks

Final Summary

Knockout.js is a stable and lightweight MVVM library.

Great for dynamic forms and data-binding-heavy UIs.

Its lifecycle and reactivity rely on observables.

Ideal for enterprise legacy systems.

Still valuable where simple declarative bindings are enough.

Faq

Is Knockout.js still used?

Yes - many enterprise systems rely on it long-term.

Does KO support two-way binding?

Yes, via `value` and `observable()`.

Can KO be used with modern bundlers?

Yes, via npm installations.

Is Knockout a framework?

No - it is a lightweight MVVM library.

Can KO interoperate with React/Vue?

Yes, for embedding legacy KO widgets.

Code Sample Descriptions

1

Knockout.js Simple Counter

<div class="container" data-bind="css: isDark() ? 'dark-theme' : 'light-theme'">
    <h2>Counter: <span data-bind="text: count"></span></h2>
    <div>
        <button data-bind="click: increment">+</button>
        <button data-bind="click: decrement">-</button>
        <button data-bind="click: reset">Reset</button>
    </div>
    <button data-bind="click: toggleTheme">Switch to <span data-bind="text: isDark() ? 'Light' : 'Dark'"></span> Theme</button>
</div>

<script>
function CounterViewModel() {
    this.count = ko.observable(0);
    this.isDark = ko.observable(false);

    this.increment = () => { this.count(this.count() + 1); };
    this.decrement = () => { this.count(this.count() - 1); };
    this.reset = () => { this.count(0); };
    this.toggleTheme = () => { this.isDark(!this.isDark()); };
}
ko.applyBindings(new CounterViewModel());
</script>

<style>
.dark-theme { background-color: #222; color: #eee; padding: 1em; }
.light-theme { background-color: #fff; color: #000; padding: 1em; }
button { margin: 0.25em; padding: 0.5em 1em; }
</style>

Basic counter with increment, decrement, reset, and theme toggle.

Let’s Try →
2

Knockout.js Counter with Step

<div class="container" data-bind="css: isDark() ? 'dark-theme' : 'light-theme'">
    <h2>Counter: <span data-bind="text: count"></span></h2>
    <div>
        <button data-bind="click: increment">+ <span data-bind="text: step"></span></button>
        <button data-bind="click: decrement">- <span data-bind="text: step"></span></button>
        <button data-bind="click: reset">Reset</button>
    </div>
    <button data-bind="click: toggleTheme">Switch Theme</button>
</div>

<script>
function CounterViewModel() {
    this.count = ko.observable(0);
    this.step = ko.observable(5);
    this.isDark = ko.observable(false);

    this.increment = () => { this.count(this.count() + this.step()); };
    this.decrement = () => { this.count(this.count() - this.step()); };
    this.reset = () => { this.count(0); };
    this.toggleTheme = () => { this.isDark(!this.isDark()); };
}
ko.applyBindings(new CounterViewModel());
</script>

Counter that increments/decrements by a custom step value.

Let’s Try →
3

Knockout.js Counter with Min/Max

<div class="container" data-bind="css: isDark() ? 'dark-theme' : 'light-theme'">
    <h2>Counter: <span data-bind="text: count"></span></h2>
    <div>
        <button data-bind="click: increment">+</button>
        <button data-bind="click: decrement">-</button>
        <button data-bind="click: reset">Reset</button>
    </div>
    <button data-bind="click: toggleTheme">Toggle Theme</button>
</div>

<script>
function CounterViewModel() {
    this.count = ko.observable(0);
    this.min = 0;
    this.max = 10;
    this.isDark = ko.observable(false);

    this.increment = () => { if(this.count() < this.max) this.count(this.count() + 1); };
    this.decrement = () => { if(this.count() > this.min) this.count(this.count() - 1); };
    this.reset = () => { this.count(0); };
    this.toggleTheme = () => { this.isDark(!this.isDark()); };
}
ko.applyBindings(new CounterViewModel());
</script>

Counter with maximum and minimum limits.

Let’s Try →
4

Knockout.js Counter with History

<div class="container" data-bind="css: isDark() ? 'dark-theme' : 'light-theme'">
    <h2>Counter: <span data-bind="text: count"></span></h2>
    <div>
        <button data-bind="click: increment">+</button>
        <button data-bind="click: decrement">-</button>
        <button data-bind="click: reset">Reset</button>
    </div>
    <p>History: <span data-bind="foreach: history"><span data-bind="text: $data"></span> </span></p>
    <button data-bind="click: toggleTheme">Toggle Theme</button>
</div>

<script>
function CounterViewModel() {
    this.count = ko.observable(0);
    this.history = ko.observableArray([]);
    this.isDark = ko.observable(false);

    this.increment = () => { this.count(this.count() + 1); this.history.push(this.count()); };
    this.decrement = () => { this.count(this.count() - 1); this.history.push(this.count()); };
    this.reset = () => { this.count(0); this.history.push(this.count()); };
    this.toggleTheme = () => { this.isDark(!this.isDark()); };
}
ko.applyBindings(new CounterViewModel());
</script>

Counter that keeps track of previous values.

Let’s Try →
5

Knockout.js Counter with Auto Increment

<div class="container" data-bind="css: isDark() ? 'dark-theme' : 'light-theme'">
    <h2>Counter: <span data-bind="text: count"></span></h2>
    <div>
        <button data-bind="click: increment">+</button>
        <button data-bind="click: decrement">-</button>
        <button data-bind="click: reset">Reset</button>
        <button data-bind="click: toggleAuto">Start/Stop Auto</button>
    </div>
    <button data-bind="click: toggleTheme">Toggle Theme</button>
</div>

<script>
function CounterViewModel() {
    this.count = ko.observable(0);
    this.isDark = ko.observable(false);
    this.auto = false;
    this.timer = null;

    this.increment = () => { this.count(this.count() + 1); };
    this.decrement = () => { this.count(this.count() - 1); };
    this.reset = () => { this.count(0); };
    this.toggleTheme = () => { this.isDark(!this.isDark()); };
    this.toggleAuto = () => {
        this.auto = !this.auto;
        if(this.auto) this.timer = setInterval(this.increment, 1000);
        else clearInterval(this.timer);
    };
}
ko.applyBindings(new CounterViewModel());
</script>

Counter that can auto-increment every second.

Let’s Try →
6

Knockout.js Counter with Double Increment

<div class="container" data-bind="css: isDark() ? 'dark-theme' : 'light-theme'">
    <h2>Counter: <span data-bind="text: count"></span></h2>
    <div>
        <button data-bind="click: increment">+</button>
        <button data-bind="click: doubleIncrement">++</button>
        <button data-bind="click: decrement">-</button>
        <button data-bind="click: reset">Reset</button>
    </div>
    <button data-bind="click: toggleTheme">Toggle Theme</button>
</div>

<script>
function CounterViewModel() {
    this.count = ko.observable(0);
    this.isDark = ko.observable(false);

    this.increment = () => { this.count(this.count() + 1); };
    this.doubleIncrement = () => { this.count(this.count() + 2); };
    this.decrement = () => { this.count(this.count() - 1); };
    this.reset = () => { this.count(0); };
    this.toggleTheme = () => { this.isDark(!this.isDark()); };
}
ko.applyBindings(new CounterViewModel());
</script>

Counter that increments by 2 on a special button.

Let’s Try →
7

Knockout.js Counter with Even/Odd Indicator

<div class="container" data-bind="css: isDark() ? 'dark-theme' : 'light-theme'">
    <h2>Counter: <span data-bind="text: count"></span> (<span data-bind="text: parity"></span>)</h2>
    <div>
        <button data-bind="click: increment">+</button>
        <button data-bind="click: decrement">-</button>
        <button data-bind="click: reset">Reset</button>
    </div>
    <button data-bind="click: toggleTheme">Toggle Theme</button>
</div>

<script>
function CounterViewModel() {
    this.count = ko.observable(0);
    this.isDark = ko.observable(false);

    this.increment = () => { this.count(this.count() + 1); };
    this.decrement = () => { this.count(this.count() - 1); };
    this.reset = () => { this.count(0); };
    this.toggleTheme = () => { this.isDark(!this.isDark()); };

    this.parity = ko.computed(() => this.count() % 2 === 0 ? 'Even' : 'Odd');
}
ko.applyBindings(new CounterViewModel());
</script>

Shows whether the current count is even or odd.

Let’s Try →
8

Knockout.js Counter with LocalStorage

<div class="container" data-bind="css: isDark() ? 'dark-theme' : 'light-theme'">
    <h2>Counter: <span data-bind="text: count"></span></h2>
    <div>
        <button data-bind="click: increment">+</button>
        <button data-bind="click: decrement">-</button>
        <button data-bind="click: reset">Reset</button>
    </div>
    <button data-bind="click: toggleTheme">Toggle Theme</button>
</div>

<script>
function CounterViewModel() {
    this.count = ko.observable(parseInt(localStorage.getItem('count') || 0));
    this.isDark = ko.observable(false);

    this.increment = () => { this.count(this.count() + 1); localStorage.setItem('count', this.count()); };
    this.decrement = () => { this.count(this.count() - 1); localStorage.setItem('count', this.count()); };
    this.reset = () => { this.count(0); localStorage.setItem('count', 0); };
    this.toggleTheme = () => { this.isDark(!this.isDark()); };
}
ko.applyBindings(new CounterViewModel());
</script>

Persists counter value in localStorage.

Let’s Try →
9

Knockout.js Counter with Color Themes

<div class="container" data-bind="css: theme()">
    <h2>Counter: <span data-bind="text: count"></span></h2>
    <div>
        <button data-bind="click: increment">+</button>
        <button data-bind="click: decrement">-</button>
        <button data-bind="click: reset">Reset</button>
    </div>
    <button data-bind="click: toggleTheme">Switch Theme</button>
</div>

<script>
function CounterViewModel() {
    this.count = ko.observable(0);
    this.themes = ['light-theme','dark-theme','blue-theme'];
    this.current = 0;
    this.theme = ko.observable(this.themes[this.current]);

    this.increment = () => { this.count(this.count() + 1); };
    this.decrement = () => { this.count(this.count() - 1); };
    this.reset = () => { this.count(0); };
    this.toggleTheme = () => { this.current = (this.current + 1) % this.themes.length; this.theme(this.themes[this.current]); };
}
ko.applyBindings(new CounterViewModel());
</script>

Counter that cycles through multiple color themes.

Let’s Try →

Frequently Asked Questions about Knockout-js

What is Knockout-js?

Knockout.js is a lightweight JavaScript library that uses the MVVM (Model-View-ViewModel) pattern to create responsive, data-driven UIs with declarative bindings. It emphasizes simplicity, observables, and automatic UI updates.

What are the primary use cases for Knockout-js?

Data-driven dashboards. Forms with heavy user interaction. Enterprise legacy SPA systems. MVVM-style large UI logic. Low-dependency applications where frameworks like React/Vue are unnecessary

What are the strengths of Knockout-js?

Very lightweight (~60 KB). Simple learning curve. Great for forms, UIs with lots of data-binding. No virtual DOM - direct DOM binding. Excellent backward compatibility

What are the limitations of Knockout-js?

Not ideal for large modular SPAs compared to modern frameworks. Manual component structure. Bindings can get messy for complex pages. Lacks modern ecosystem of React/Vue. No built-in state management or routing

How can I practice Knockout-js typing speed?

CodeSpeedTest offers 9+ real Knockout-js code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.