Reason
  • Docs
  • Try
  • API
  • Community
  • Blog
  • Languages iconEnglish
    • 日本語
    • Deutsch
    • Español
    • Français
    • 한국어
    • Português (Brasil)
    • Русский
    • Українська
    • 中文
    • 繁體中文
    • Help Translate
  • GitHub

›Language Basics

Intro

  • What & Why
  • Getting started

Setup

  • Installation
  • Editor Plugins
  • Format (refmt)

Language Basics

  • Overview
  • Let Bindings
  • Primitives
  • Basic Structures
  • Types
  • Records
  • Variants
  • Options and nullability
  • Functions
  • Recursion
  • Destructuring
  • Pattern Matching
  • Mutable Bindings
  • Loops
  • Modules

Advanced Features

  • JSX
  • External
  • Exception
  • Object

JavaScript

  • Melange
  • Interop
  • Syntax Cheatsheet
  • Pipe First
  • Promise
  • Libraries
  • Converting from JS

Extra

  • Frequently Asked Questions
  • Extra Goodies
  • REPL (rtop)
Edit

Loops

Quick overview: Loops

Loops are discouraged in most cases. Instead functional programming patterns like map, filter, or reduce can usually be used in their place.

For Loops

For loops use the for, in, and to keywords. For loops always increment or decrement a counter by one on each iteration. This increment cannot be changed, use while loops for more control over the increment.

let x = 1;
let y = 5;

for (i in x to y) {
  print_int(i);
  print_string(" ");
};
/* Prints: 1 2 3 4 5 */

The reverse direction is also possible using the downto keyword:

for (i in y downto x) {
  print_int(i);
  print_string(" ");
};
/* Prints: 5 4 3 2 1 */

While Loops

While loops allow executing code until a certain condition is met. It is not restricted to counting between two integers like for loops.

It is common to use refs with while loops.

let i = ref(1);

while (i^ <= 5) {
  print_int(i^);
  print_string(" ");
  i := i^ + 2;
};
/* Prints: 1 3 5 */

Break

There is no break or early return behavior in Reason. In order to achieve something similar create a boolean ref:

let break = ref(false);

while (!break^ && condition) {
  if (shouldBreak()) {
    break := true;
  } else {
    /* normal code */
  };
};
← Mutable BindingsModules →
  • For Loops
  • While Loops
    • Break