5 ms·
How do immutable variables work with something like a for loop?
by voidUpdate 11mo ago
How do immutable variables work with something like a for loop?
- foxygen 11mo agoYou use something else like map/filter/reduce or recursion.
- tgv 11mo agoUnless you need the index, you can write: for (const x of iterable) { ... } or for (const attribute in keyValueMap) { ... }. However, loops often change state, so it's probably not the way to go if you can't change any variable.
- Cthulhu_ 11mo agoIf you need the index, you can use .keys() or .entries() on the iterable, e.g. for (const [index, value] of ["a", "b", "c", "d", "e"].entries()) { console.log(index, value); } Or forEach, or map. Basically, use a higher level language. The traditional for loop tells an interpreter "how" to do things, but unless you need the low level performance, it's better to tell it "what", that is, use more functional programming constructs. This is also the way to go for immutable variables, generally speaking.
- tgv 11mo agoThere's no difference between for (x of a) stmt; and a.forEach(x => stmt), except for scope, and lack of flow control in forEach. There's no reason to prefer .forEach(). I don't see how it is "more functional."
- tantalor 11mo agoIs TFA (or anyone else for that matter) actually concerned with "immutable variables"? e.g., `let i = 0; i++;` They seem to be only worried about modifying objects, not reassignment of variables.
- voidUpdate 11mo agoLooks like Rust is https://doc.rust-lang.org/stable/std/keyword.let.html https://doc.rust-lang.org/stable/std/keyword.let.html
- macintux 11mo agoErlang doesn't allow variable reassignment. Elixir apparently does, but I've never played with it.
- ruined 11mo agotypescript handles that well already
- Cthulhu_ 11mo agoThat's probably because reassignment is already covered by using `const`. Of course, it doesn't help that the immutable modifier for Swift is `let`. But also, in Swift, if you assign a list via `let`, the list is also immutable.
- bastawhiz 11mo agoSince sibling comments have pointed out the various ES5 methods and ES6 for-of loops, I'll note two things: 1. This isn't an effort to make all variables `const`. It's an effort to make all objects immutable. You can still reassign any variable, just not mutate objects on the heap (by default) 2. Recursion still works ;)
- turboponyy 11mo ago`for` loops are a superfluous language feature if your collections have `map` for transformations and `forEach` for producing side effects
- nurettin 11mo agoThey don't work. The language has to provide list and map operations to compensate.