Learn ZIG-WASM with Real Code Examples
Updated Nov 25, 2025
Code Sample Descriptions
1
Simple Zig WebAssembly Program
# zig/demo/main.zig
const std = @import("std");
pub export fn main() void {
std.debug.print("Hello, Zig WASM!\n", .{});
}
A basic Zig program compiled to WebAssembly that prints 'Hello, Zig WASM!' to the console.
2
Zig WASM Add Two Numbers
# zig/demo/add.zig
const std = @import("std");
pub export fn add(a: i32, b: i32) void {
std.debug.print("Sum: {d}\n", .{a + b});
}
Adds two integers and prints the result.
3
Zig WASM Multiply Two Numbers
# zig/demo/multiply.zig
const std = @import("std");
pub export fn multiply(a: i32, b: i32) void {
std.debug.print("Product: {d}\n", .{a * b});
}
Multiplies two integers and prints the result.
4
Zig WASM Fibonacci
# zig/demo/fibonacci.zig
const std = @import("std");
fn fib(n: i32) i32 {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
pub export fn fibonacci(n: i32) void {
std.debug.print("Fibonacci: {d}\n", .{fib(n)});
}
Calculates the nth Fibonacci number recursively and prints it.
5
Zig WASM Factorial
# zig/demo/factorial.zig
const std = @import("std");
fn factorial(n: i32) i32 {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
pub export fn factorial(n: i32) void {
std.debug.print("Factorial: {d}\n", .{factorial(n)});
}
Calculates factorial recursively and prints the result.
6
Zig WASM Even Check
# zig/demo/even.zig
const std = @import("std");
pub export fn isEven(n: i32) void {
if (n % 2 == 0) {
std.debug.print("Even\n", .{});
} else {
std.debug.print("Odd\n", .{});
}
}
Checks if a number is even and prints the result.
7
Zig WASM Maximum of Two Numbers
# zig/demo/max.zig
const std = @import("std");
pub export fn max(a: i32, b: i32) void {
if (a > b) {
std.debug.print("Max: {d}\n", .{a});
} else {
std.debug.print("Max: {d}\n", .{b});
}
}
Finds the maximum of two numbers and prints it.
8
Zig WASM Minimum of Two Numbers
# zig/demo/min.zig
const std = @import("std");
pub export fn min(a: i32, b: i32) void {
if (a < b) {
std.debug.print("Min: {d}\n", .{a});
} else {
std.debug.print("Min: {d}\n", .{b});
}
}
Finds the minimum of two numbers and prints it.
9
Zig WASM Toggle Boolean
# zig/demo/toggle.zig
const std = @import("std");
var state: bool = false;
pub export fn toggle() void {
state = !state;
if (state) {
std.debug.print("ON\n", .{});
} else {
std.debug.print("OFF\n", .{});
}
}
Toggles a boolean value and prints ON/OFF.
10
Zig WASM Print Array
# zig/demo/array.zig
const std = @import("std");
pub export fn printArray(arr: [5]i32) void {
for (arr) |val| {
std.debug.print("{d} ", .{val});
}
std.debug.print("\n", .{});
}
Prints elements of an array.