Skip to content

Add for and while loops to the syntax widget #1023

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions misc_docs/syntax/language_for.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
---
id: "for"
keywords: ["for", "loop"]
name: "for loop"
summary: "This is the `for` loop."
category: "languageconstructs"
---

ReScript supports `for` loops.

For loops can iterate from a starting value up to (and including) the ending value via the `to` keyword, or in the opposite direction via the `downto` keyword.

### Example

<CodeTab labels={["ReScript", "JS Output"]}>

```res
// Using `to`
for x in 1 to 3 {
Console.log(x)
}

// Using `downto`
for y in 3 downto 1 {
Console.log(y)
}
```

```js
for(var x = 1; x <= 3; ++x){
console.log(x);
}

for(var y = 3; y >= 1; --y){
console.log(y);
}
```

</CodeTab>


### References

* [For Loops](control-flow.md#for-loops)

50 changes: 50 additions & 0 deletions misc_docs/syntax/language_while.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
---
id: "while"
keywords: ["while", "loop"]
name: "while loop"
summary: "This is the `while` loop."
category: "languageconstructs"
---

ReScript supports `while` loops. While loops execute its body code block while its condition is true.

ReScript does not have the `break` keyword, but you can easily break out of a while loop by using a mutable binding.

### Example

<CodeTab labels={["ReScript", "JS Output"]}>

```res
let break = ref(false)

while !break.contents {
if Math.random() > 0.3 {
break := true
} else {
Console.log("Still running")
}
}

```

```js
let $$break = {
contents: false
};

while (!$$break.contents) {
if (Math.random() > 0.3) {
$$break.contents = true;
} else {
console.log("Still running");
}
};
```

</CodeTab>


### References

* [While Loops](control-flow.md#while-loops)