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. Hack

Learn Hack - 10 Code Examples & CST Typing Practice Test

Hack is a programming language developed by Facebook as a dialect of PHP. It adds static typing, enhanced performance, and modern programming features while maintaining compatibility with PHP, enabling rapid development of large-scale web applications.

View all 10 Hack code examples →
Hack Counter and Theme ToggleHack Fibonacci SequenceHack Factorial CalculatorHack Prime CheckerHack Sum of ArrayHack Reverse StringHack Multiplication TableHack Celsius to FahrenheitHack Simple Alarm SimulationHack Random Walk Simulation

Learn HACK with Real Code Examples

Updated Nov 20, 2025

Explain

Hack combines dynamic typing of PHP with optional static typing.

It allows gradual typing, meaning developers can mix typed and untyped code.

Designed for web development at scale, particularly within the Facebook ecosystem.

Core Features

Gradual typing system

Async programming with awaitables

Generics and type annotations

Shape types for structured data

Hack collections (vec, dict, keyset)

Basic Concepts Overview

Gradual typing (dynamic + static)

Collections (vec, dict, keyset)

Async programming with awaitables

Functions, classes, and traits

Shapes and generics for structured data

Project Structure

src/ - main Hack codebase

lib/ - reusable libraries

tests/ - unit and integration tests

docs/ - project documentation

configs/ - HHVM and server configurations

Building Workflow

Write Hack code with optional types

Run using HHVM interpreter or server

Test functions, classes, and async tasks

Compile or run scripts for production

Integrate with PHP code if necessary

Difficulty Use Cases

Beginner: small Hack scripts and functions

Intermediate: collections and async functions

Advanced: generics, shapes, and type-safe code

Expert: large-scale web application architecture

Migration: PHP to Hack gradual typing adoption

Comparisons

Adds static typing to PHP

Runs on HHVM instead of standard PHP engine

Better for large-scale web applications

Supports async and modern language features

Smaller ecosystem than mainstream PHP

Versioning Timeline

2014 - Hack created by Facebook

2015 - HHVM integration stabilized

2016 - Async programming and collections introduced

2018 - Generics, shapes, and typechecker improvements

2020s - Ongoing maintenance and ecosystem updates

Glossary

Gradual typing: mix of static and dynamic types

HHVM: HipHop Virtual Machine for Hack/PHP

Collections: vec, dict, keyset types

Awaitable: async result to be awaited

Shape: structured data type with fixed fields

Installation Setup

Install HHVM on your system

Set up Hack language support

Configure environment paths

Test sample Hack scripts

Integrate with web server for development

Environment Setup

Install HHVM

Configure hhconfig

Install Hack development tools

Set PATH for HHVM binaries

Test sample Hack scripts

Config Files

hhconfig - project typecheck configuration

src/ - main Hack source code

lib/ - reusable libraries

tests/ - unit and integration tests

configs/ - HHVM server configurations

Cli Commands

hh_client - typecheck Hack project

hh_server - start Hack typecheck server

hhvm script.hack - run Hack script

hhvm -web - run Hack web server

hh_client --json - get typecheck results

Internationalization

Supports UTF-8 strings

Works with global databases and APIs

Data formats can handle internationalized content

Compatible with international libraries in PHP

No built-in localization engine; relies on PHP ecosystem

Accessibility

Open-source and cross-platform via HHVM

Documentation available online

Community support through forums and GitHub

Gradual typing eases transition for PHP developers

Works well in large codebases and teams

Ui Styling

Web applications styled with standard HTML/CSS/JS

Hack used for backend logic

Optional templating engines for frontend

Integration with frameworks like HackMVC

No built-in UI styling in language itself

State Management

Variables with optional static types

Collections for structured data

Async functions for managing concurrent state

Shapes for structured object-like data

Modules encapsulate reusable logic

Data Management

Hack collections (vec, dict, keyset)

Typed variables and function arguments

Shapes for structured records

Persistent data via databases or files

Async pipelines for dynamic data handling

Architecture

Runs on HHVM (HipHop Virtual Machine)

Supports both static and dynamic typing

Compiles Hack code for efficient execution

Supports asynchronous I/O

Type system integrated at runtime and compile-time

Rendering Model

Hack code executed on HHVM runtime

Static typechecking at compile time via hh_client

Dynamic execution for untyped sections

Async functions scheduled via event loop

Integration with PHP libraries where needed

Architectural Patterns

Web backend services

Async event-driven programming

Type-safe APIs

PHP-Hack mixed codebases

Large-scale modular application design

Real World Architectures

Facebook backend services

High-performance REST/GraphQL APIs

Async data processing pipelines

Large-scale web applications

PHP codebases upgraded to Hack gradually

Design Principles

Gradual typing for backward compatibility

High-performance web execution on HHVM

Async and concurrent programming support

Compatibility with PHP ecosystem

Modern language constructs for maintainable code

Scalability Guide

Use Hack collections for memory efficiency

Employ async functions for concurrent requests

Modularize code into reusable components

Leverage HHVM JIT compilation for performance

Typecheck code regularly to prevent runtime errors

Migration Guide

Gradually add type annotations to PHP code

Replace legacy PHP constructs with Hack equivalents

Adopt Hack collections for structured data

Refactor code for async/await patterns

Test with HHVM typechecker and runtime

Performance Notes

Optimized via HHVM JIT compilation

Static typing improves runtime safety

Async programming reduces blocking

Use Hack collections for efficient memory usage

Gradual typing allows incremental performance tuning

Security Notes

Static typing helps prevent runtime type errors

Validate user input and outputs

Use HHVM security best practices

Avoid unsafe PHP function usage

Implement secure async operations

Monitoring Analytics

Monitor async workflows and performance

Check HHVM server logs

Validate type safety with hh_client

Profile resource usage

Audit deployed Hack services

Code Quality

Use static typing for clarity and safety

Organize code into modules and namespaces

Document shapes, generics, and functions

Write unit and integration tests

Leverage typechecker to catch errors early

Practical Examples

Building a social media backend

Creating type-safe REST APIs

Async data processing pipelines

Integrating Hack with existing PHP code

High-performance web services

Troubleshooting

Check type errors in static analysis

Ensure HHVM runtime is configured

Debug async/await logic

Validate PHP compatibility

Test integration with existing code

Testing Guide

Run hh_client for type checking

Execute HackTest unit tests

Test async workflows

Validate PHP-Hack interoperability

Monitor runtime behavior in HHVM

Deployment Options

HHVM server for web applications

Command-line Hack scripts

Async services and daemons

Integration in PHP ecosystems

High-performance backend APIs

Tools Ecosystem

HHVM runtime

Hack typechecker (hh_client)

Hack language server (LSP)

IDEs with Hack support (VS Code, PhpStorm)

Unit testing frameworks (HackTest)

Integrations

Existing PHP codebases

REST and GraphQL APIs

Databases like MySQL and PostgreSQL

Async services and message queues

Web frameworks compatible with HHVM

Productivity Tips

Gradually add type annotations

Use async/await for concurrency

Modularize reusable logic

Test often with typechecker

Leverage Hack collections and shapes

Challenges

Migrate a PHP module to Hack

Implement a type-safe REST API

Build an async data processing service

Integrate Hack with existing PHP backend

Optimize code for HHVM performance

Learning Path

Learn PHP basics if not already familiar

Understand Hack's gradual typing

Practice collections, shapes, and generics

Explore async programming with awaitables

Build sample web applications using HHVM

Skill Improvement Plan

Week 1: Hack syntax and typed variables

Week 2: Functions, collections, and shapes

Week 3: Async programming and awaitables

Week 4: Integrate Hack with PHP codebases

Week 5: Build and deploy small web services

Interview Questions

What is Hack and how does it relate to PHP?

Explain gradual typing in Hack

How do Hack collections work?

Describe async/await in Hack

What are Hack shapes and generics?

Cheat Sheet

function foo(int $x): string { } - typed function

$var = vec[1,2,3]; - Hack vector

await asyncFunction(); - async call

shape('name' => string, 'age' => int) - structured data

hh_client - typecheck project

Books

Hack Programming Guide

Mastering Hack for Web Development

Hack by Example

Hack and HHVM in Practice

Advanced Hack Programming Techniques

Tutorials

Getting Started with Hack

Gradual Typing and Collections

Async Programming in Hack

Shapes, Generics, and Type Annotations

Building Web Applications with Hack

Official Docs

Hack Official Documentation

HHVM Documentation

Hack GitHub Repository

Community Links

Hack GitHub repository

HHVM community forums

Stack Overflow Hack tag

Facebook developer resources

Community tutorials and blogs

Community Support

Hack GitHub repository

Facebook developer resources

HHVM community forums

Stack Overflow Hack tag

Hack language documentation

Monetization

High-performance web apps

Backend services for large-scale systems

Enterprise PHP modernization projects

Consulting on Hack adoption

Training for Hack developers

Future Roadmap

Maintain compatibility with PHP

Enhance async and concurrent features

Expand collection types and shapes

Improve HHVM performance and tooling

Grow community adoption and support

When Not To Use

Small-scale PHP projects

Environments without HHVM support

Non-web applications

Projects requiring extensive PHP library support

Legacy PHP hosting without Hack compatibility

Final Summary

Hack is a modern dialect of PHP with static typing and async support.

Runs on HHVM and enables type-safe, high-performance web applications.

Compatible with PHP codebases while adding modern language features.

Ideal for large-scale, maintainable web development.

Faq

Is Hack still used?

Yes, primarily in Facebook and HHVM-based projects.

Can Hack run on standard PHP?

No, it requires HHVM runtime.

Why learn Hack today?

For type-safe, high-performance PHP web development.

Is Hack open-source?

Yes, available under MIT license.

Code Sample Descriptions

1

Hack Counter and Theme Toggle

<?hh

<<__EntryPoint>>
function main(): void {
    $counter = 0;
    $isDark = false;

    function updateUI(): void {
        global $counter, $isDark;
        echo "Counter: $counter\n";
        echo "Theme: " . ($isDark ? "Dark" : "Light") . "\n";
    }

    function increment(): void {
        global $counter;
        $counter += 1;
        updateUI();
    }

    function decrement(): void {
        global $counter;
        $counter -= 1;
        updateUI();
    }

    function reset(): void {
        global $counter;
        $counter = 0;
        updateUI();
    }

    function toggleTheme(): void {
        global $isDark;
        $isDark = !$isDark;
        updateUI();
    }

    // Simulate actions
    updateUI();
    increment();
    increment();
    toggleTheme();
    decrement();
    reset();
}

Demonstrates a simple counter with theme toggling using Hack variables, functions, and conditional statements.

Let’s Try →
2

Hack Fibonacci Sequence

<?hh
function fib(int $n): int {
    return $n < 2 ? $n : fib($n-1) + fib($n-2);
}
<<__EntryPoint>>
function main(): void {
    for ($i = 0; $i < 10; $i++) {
        echo fib($i) . "\n";
    }
}

Generates first 10 Fibonacci numbers using recursion.

Let’s Try →
3

Hack Factorial Calculator

<?hh
function factorial(int $n): int {
    return $n === 0 ? 1 : $n * factorial($n - 1);
}
<<__EntryPoint>>
function main(): void {
    echo factorial(5) . "\n";
}

Calculates factorial of a number using recursion.

Let’s Try →
4

Hack Prime Checker

<?hh
function isPrime(int $n): bool {
    if ($n < 2) return false;
    for ($i = 2; $i < $n; $i++) {
        if ($n % $i === 0) return false;
    }
    return true;
}
<<__EntryPoint>>
function main(): void {
    echo isPrime(13) ? "Prime\n" : "Not Prime\n";
}

Checks if a number is prime.

Let’s Try →
5

Hack Sum of Array

<?hh
<<__EntryPoint>>
function main(): void {
    $nums = vec[1,2,3,4,5];
    $sum = array_sum($nums);
    echo $sum . "\n";
}

Calculates sum of an array of numbers.

Let’s Try →
6

Hack Reverse String

<?hh
<<__EntryPoint>>
function main(): void {
    $s = "HELLO";
    echo strrev($s) . "\n";
}

Reverses a string.

Let’s Try →
7

Hack Multiplication Table

<?hh
<<__EntryPoint>>
function main(): void {
    $n = 5;
    for ($i = 1; $i <= 10; $i++) {
        echo "$n x $i = " . ($n * $i) . "\n";
    }
}

Prints multiplication table of a number.

Let’s Try →
8

Hack Celsius to Fahrenheit

<?hh
<<__EntryPoint>>
function main(): void {
    $c = 25;
    $f = ($c * 9 / 5) + 32;
    echo $f . "\n";
}

Converts Celsius to Fahrenheit.

Let’s Try →
9

Hack Simple Alarm Simulation

<?hh
<<__EntryPoint>>
function main(): void {
    $temp = 80;
    $thresh = 75;
    echo ($temp > $thresh ? "Alarm: Temperature Too High!\n" : "Temperature Normal\n");
}

Simulates an alarm if a threshold is exceeded.

Let’s Try →
10

Hack Random Walk Simulation

<?hh
<<__EntryPoint>>
function main(): void {
    $steps = 10;
    $pos = 0;
    for ($i = 0; $i < $steps; $i++) {
        $pos += (rand(0,1) === 0 ? -1 : 1);
        echo $pos . "\n";
    }
}

Simulates a 1D random walk.

Let’s Try →

Frequently Asked Questions about Hack

What is Hack?

Hack is a programming language developed by Facebook as a dialect of PHP. It adds static typing, enhanced performance, and modern programming features while maintaining compatibility with PHP, enabling rapid development of large-scale web applications.

What are the primary use cases for Hack?

Large-scale web application development. Maintaining and modernizing PHP codebases. Developing scalable backend services. Improving code safety with static typing. Rapid iteration and prototyping in web projects

What are the strengths of Hack?

Improves reliability with static typing. Maintains compatibility with existing PHP code. Enhances code readability and maintainability. Optimized for large-scale web applications. Supports modern programming patterns

What are the limitations of Hack?

Primarily used within Facebook or HHVM ecosystems. Smaller community compared to mainstream PHP. Requires HHVM runtime, not standard PHP engine. Not ideal for small-scale or non-web projects. Learning curve for developers new to static typing

How can I practice Hack typing speed?

CodeSpeedTest offers 10+ real Hack 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.