Pushing to an array from inside a for loop

I’m trying to push to an array from inside a for loop.

The simplest approach does not seem to be valid:

let foo = [1, 2]

for index in 0 to 6 {
	open Js.Array2
	foo->push(index)
}

It results in an error:

This has type: int
Somewhere wanted: unit

I’ve found that binding the return value of the push call to a let fixes the issue, and creates the JS output I’d expect:

let foo = [1, 2]

for index in 0 to 6 {
	open Js.Array2
	let _ = foo->push(index)
}

But I don’t understand why. Would somebody be able to point me to some documentation, or explain? This feels like the wrong answer.

Thanks :slight_smile:.

1 Like

You can also do arr->push(item)->ignore.

push returns the new length of the array: Array.prototype.push() - JavaScript | MDN

Many are used to ignore it silently in JS. ReScript makes you explicitly acknowledge that you’ve ignoring the return value. It’s harmless in this case but sometime it prevents bugs.

4 Likes

@chenglou Got it. Thank you for explaining!

2 Likes